这是一个递归程序,用于测试句子是否是回文.如果我写“bob”,它将正确运行,但因为大写字母和符号而不是“Madam I’m Adam”.我们需要使用干净的字符串方法(?)来消除空格,符号和大写字母.这就是我所拥有的,但我不相信我已经正确实现了它.有人能告诉我如何改进/解决这个问题吗? (是的,我看过互联网)
import java.util.Scanner;
public class Palindromes {
public static boolean isaPalindrome(String s) {
String cleanedString = clean(s);
if (s.length() == 0 || s.length() == 1)
return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isaPalindrome(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
System.out.print("Enter a palindrome to test: ");
Scanner console = new Scanner(System.in);
String inStr = console.nextLine();
if (isaPalindrome(inStr)) {
System.out.printf("The input string, %s, is a palindrome.\n",
inStr);
reverseStr(inStr); // must be recursive!
System.out.println();
} else {
System.out.printf("The input string, %s, is not a palindrome.\n",
inStr);
}
}
private static String clean(String s) {
String cleaned = "";
return cleaned;
}
private static String reverseStr(String inStr) {
if ((null == inStr) || (inStr.length() <= 1)) {
return inStr;
}
return reverseStr(inStr.substring(1)) + inStr.charAt(0);
}
}
最佳答案 您的递归方法isaPalindrome是正确的.如果你想进一步改进它,我建议你避免使用subString为你的递归调用创建参数,这将创建太多的字符串.
而是跟踪您要比较的原始字符串中字符的位置:
public static boolean isaPalindrome(String s, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) return true;
if (s.charAt(leftIndex) == s.charAt(rightIndex))
return isaPalindrome(s, leftIndex + 1, rightIndex - 1);
return false;
}
你可以调用方法:isaPalindrome(inStr,0,inStr.length() – 1)
至于clean方法,可以使用toLowerCase和Character.isLetter方法来处理原始字符串.
private static String clean(String s) {
String lowerCaseString = s.toLowerCase();
StringBuffer result = new StringBuffer();
for (int i = 0; i < lowerCaseString.length(); ++i) {
if (Character.isLetter(lowerCaseString.charAt(i))) {
result.append(lowerCaseString.charAt(i));
}
}
return result.toString();
}