Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Here is a recursive method that returns the smallest character in a string

ID: 3846428 • Letter: J

Question

JAVA:

Here is a recursive method that returns the smallest character in a string: // return smallest character in s, e.g. getMinChar("difference") would return 'c' static char getMinChar(String s) { if (s.length() == 1) return s.charAt(0); if (getMinChar(s.substring(1)) > s.charAt(0)) return s.charAt(0); else return getMinChar(s.substring(1)); } The method returns the correct value but it can be extremely slow when s is a long string. Recode getMinChar so that it’s more efficient by reducing the number of recursive calls. Your code should still be recursive. There is no need to make major changes to the algorithm.

Explanation / Answer

static char smallestLetter(String s) {
if (s.length() == 1)
return s.charAt(0);
else if (s.charAt(0) < s.charAt(1)) //if found less than chracter then calling recursively here..
return getMinChar(s.substring(0) + s.substring(2,s.length())); //calling recursively reduce lot of steps
else
return getMinChar(s.substring(1,s.length()));
}