Home > Back-end >  How do you find the alphabetically last letter of a string using recursion (no loops!) and without u
How do you find the alphabetically last letter of a string using recursion (no loops!) and without u

Time:01-19

Got something for you all.

As the title of the problem suggests, I am trying to implement a non-array, non-looping, recursive method to find the alphabetically last letter in a string.

I think that I understand the nature of the problem I'm trying to solve, but I don't know how to start with the base case and then the recursion.

Can anyone be willing to solve this problem?

In this case, I would like the following code:

//Method Definition
public static String findZenithLetter(String str) {
   //Put actual working Java code that finds the alphabetically last letter of the desired string here.
   //Use recursion, not loops! :)
   //Don't use arrays! ;)
}

//Driver Code
System.out.println(findZenithLetter("I can reach the apex, at the top of the world."))
//Should print the String "x" if implemented properly

I have tried to attempt numerous, but currently failed ways of solving this problem, including but not limited to:

  • Sorting the string by alphabetical order then finding the last letter of the new string, excluding punctuation marks.
  • Using the compareTo() method to compare two letters of the string side by side, but that has yet to work as I am so tempted to use loops, not recursion. I need a recursive method to solve this, though. :)

In the end, the best piece of code that I've written for this problem was just a drawn-out way to compute just the last character of a string and not actually THE alphabetically last character.

CodePudding user response:

This is quite simple. All you need is just iterate (in the recursion of course), and check all characters int he string with local maximum.

public static char findZenithLetter(String str) {
    return findZenithLetter(str, 0, 'a');
}

private static char findZenithLetter(String str, int i, char maxCh) {
    if (i >= str.length())
        return maxCh;

    char ch = Character.toLowerCase(str.charAt(i));

    if (Character.isLetter(ch))
        maxCh = ch > maxCh ? ch : maxCh;

    return findZenithLetter(str, i   1, maxCh);
}

CodePudding user response:

Nibble off the first character at each recursion, returning the greater of it and the greatest found in the rest of the input:

public static String findZenithLetter(String str) {
    if (str.isEmpty()) {
        return ""; // what's returned if no letters found
    }
    String next = str.substring(0, 1);
    String rest = findZenithLetter(str.substring(1));
    return Character.isLetter(next.charAt(0)) && next.compareToIgnoreCase(rest) > 0 ? next : rest;
}

See live demo.

The check for Character.isLetter() prevents non-letter characters, which may be "greater than" letters being returned.

If no letters are found, a blank is returned.

  • Related