我在将以下代码重写为递归方法而不是使用 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/