java - 将 for 循环重写为递归方法?

标签 java for-loop recursion

我在将以下代码重写为递归方法而不是使用 for 循环时遇到问题。 for 循环测试字符串“noSpaces”是否为回文(向前和向后相同)。 noSpaces 字符串没有标点符号、空格或大小写差异。

感谢您的帮助

    public boolean isRegularPalindrome(String noSpaces) {
    noSpaces = noSpaces.toUpperCase();
    String[] letters = new String[noSpaces.length()];
    for (int i = 0; i < letters.length; i++) {
        letters[i] = Character.toString(noSpaces.charAt(i));
    }

    for (int i = 0; i < letters.length / 2; i++) {
        if (!letters[i].equals(letters[letters.length - i - 1])) {
            return false;
        }
    }
    return true;
}

最佳答案

给你:

public static boolean isPalindrome(String input) {
    if (input.charAt(0) != input.charAt(input.length() - 1)) {
        // Missmatch. Not a palindrome!
        return false;
    } else if (input.length() > 1){
        // If there is more to test, continue.
        return isPalindrome(input.substring(1, input.length() - 1));
    } else {
        // All chars were tested, or 1 char input. Palindrome!
        return true;
    }
}

关于java - 将 for 循环重写为递归方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35905520/

相关文章:

Java NIO 选择器 select() 返回 0,尽管 channel 已准备就绪

java - 在 Java 中使用 Pushetta 发送推送通知会导致 403 Forbidden

Windows 批处理命令 : How to dereference FOR loop variable to check if that variable is SET in Environment Variable

C++ for循环和switch语句逻辑错误

php - 在PHP中的每个级别递归排序多维数组

jquery - Jquery 的 setTimeout 递归

Python:如何循环不同深度的列表列表?

java - 关于 Java 赋值运算符

java - 将用户输入的字符串转换为数字(int)值。

java - StringBuffer循环设置