-6

你如何测试给定的字符串是否是 Java 中的回文,而不使用任何为我做这一切的方法?

4

5 回答 5

6
String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome).reverse().toString());
于 2010-08-06T06:38:31.697 回答
5
public boolean checkPalindrome(string word){

for(int i=0 ; i < word.length()/2;i++)
{
  if(word.charAt(i) ! = word.charAt(word.length()-1-i))

      return false;
}

return true;
}
于 2010-08-06T06:45:54.410 回答
0

Java in-place palindrome check:

public static final boolean isPalindromeInPlace(String string) {
    char[] array = string.toCharArray();
    int length = array.length-1;
    int half = Math.round(array.length/2);
    char a,b;
    for (int i=length; i>=half; i--) {
        a = array[length-i];
        b = array[i];
        if (a != b) return false;
    }
    return true;
}
于 2012-01-05T16:47:49.113 回答
0

Noel 的解决方案实际上更好。但如果是为了家庭作业,你可能想要这样做:

public static boolean isPalindrome(String word) {
    int left = 0;
    int right = word.length() -1;

    while (left < right) {
        if (word.charAt(left) != word.charAt(right)) 
            return false;

        left++;
        right--;
    }

    return true;
}
于 2010-08-06T06:38:41.243 回答
-2
String str="iai";

StringBuffer sb=new StringBuffer(str);
String str1=sb.reverse().toString();
if(str.equals(str1)){
   System.out.println("polindrom");
} else {
   System.out.println("not polidrom");
}
于 2012-06-08T14:31:44.127 回答