Anzeige

16- Here is a recursive method that returns the smallest character in.docx

todd991
8. Feb 2023
16- Here is a recursive method that returns the smallest character in.docx
16- Here is a recursive method that returns the smallest character in.docx
Nächste SlideShare
Unitii stringUnitii string
Wird geladen in ... 3
1 von 2
Anzeige

Más contenido relacionado

Más de todd991(20)

Anzeige

16- Here is a recursive method that returns the smallest character in.docx

  1. 16. 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)); } a. 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. b. When you call getMinChar("") you notice that a StringIndexOutOfBoundsException is thrown. Since getMinChar()compiled fine, you deduce that StringIndexOutOfBoundsException must be an unchecked exception. What fact about exceptions allows you to deduce this Solution a) 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())); } --------------------------------------------------------------------------------------------------------------------- ---------------------------------- b) Consider if in the intermediate operations if string becomes empty or null or input parameter is "" , then StringIndexOutOfBoundsException is thrown. This exception allows to execute and exit smoothly. If we didn't thrown exception then program exits abnormally. So better to kepp checked exception.
  2. Program with exception thrown static char smallestLetter(String s) throws StringIndexOutOfBoundsException { 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 this recursively reduce lot of steps else return getMinChar(s.substring(1,s.length())); }
Anzeige