How do you determine if a String is a palindrome? [duplicate]

╄→гoц情女王★ 提交于 2019-12-13 10:12:06

问题


How do you test if a given String is a palindrome in Java, without using any methods that do it all for me?


回答1:


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



回答2:


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



回答3:


Noel's solution is actually better. But if it's for homework, you might want to do this:

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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/3421499/how-do-you-determine-if-a-string-is-a-palindrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!