我有一个检查字符串是否为回文的类。我有两个问题。
1)这是检查回文的最有效的方法吗? 2)这可以递归实现吗?
public class Words {
public static boolean isPalindrome(String word) {
String pal = null;
word = word.replace(" ", "");
pal = new StringBuffer(word).reverse().toString();
if (word.compareTo(pal) == 0) {
return true;
} else {
return false;
}
}
}有一个测试类来测试这个...怀疑它是必要的,但无论如何,如果有人愿意尝试一下,能够帮助我解决上面两个问题中的任何一个……
public class testWords {
public static void main(String[] args) {
if (Words.isPalindrome("a") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("cat") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("w o w") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome(" a ") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("mom!") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}提前感谢您的帮助和/或输入:)
发布于 2013-03-31 03:42:25
实际上,只需检查中间字符以确认它是一个回文字符就足够了,这意味着您可以将其简化为如下所示:
// Length of my string.
int length = myString.length();
// Loop over first half of string and match with opposite character.
for (int i = 0; i <= length / 2; i++) {
// If we find one that doesn't match then return false.
if (myString.charAt(i) != myString.charAt(length - 1 - i)) return false;
}
// They all match, so we have found a palindrome!
return true;递归解决方案是非常有可能的,但是它不会给你带来任何性能上的好处(而且可能不是那么好读)。
https://stackoverflow.com/questions/15722624
复制相似问题