你如何确定一个字符串是否是回文?

时间:2010-08-06 06:36:24

标签: java string palindrome

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

5 个答案:

答案 0 :(得分:6)

String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome).reverse().toString());

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}

答案 3 :(得分:0)

Java就地回文检查:

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;
}

答案 4 :(得分:-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");
}