繁体   English   中英

您如何使用递归(无循环?)而不在 Java 中使用 arrays 来查找字符串的字母顺序最后一个字母?

[英]How do you find the alphabetically last letter of a string using recursion (no loops!) and without using arrays in Java?

有东西给你们。

正如问题的标题所暗示的,我正在尝试实现一种非数组、非循环、递归的方法来查找字符串中按字母顺序排列的最后一个字母。

我认为我了解我要解决的问题的性质,但我不知道如何从基本情况开始,然后是递归。

有没有人愿意解决这个问题?

在这种情况下,我想要以下代码:

//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

我尝试了很多但目前都失败的方法来解决这个问题,包括但不限于:

  • 按字母顺序对字符串进行排序,然后找到新字符串的最后一个字母,不包括标点符号。
  • 使用 compareTo() 方法并排比较字符串的两个字母,但这还没有奏效,因为我很想使用循环,而不是递归。 不过,我需要一种递归方法来解决这个问题。 :)

最后,我为这个问题编写的最好的代码只是一种只计算字符串最后一个字符而不是实际按字母顺序排列的最后一个字符的冗长方法。

这很简单。 您所需要的只是迭代(当然是在递归中),并检查字符串中的所有字符是否具有局部最大值。

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);
}

在每次递归时蚕食第一个字符,返回它的较大者和在输入的 rest 中找到的最大者:

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;
}

查看现场演示

检查Character.isLetter()可防止返回非字母字符,这些字符可能“大于”字母。

如果没有找到字母,则返回空白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM