天天看點

如何判斷兩個字元串是否互為回文?

回文,英文 palindrome,如果該字元串的反轉與原始字元串相同,則該字元串稱為回文字元串。

比如:

  • radar
  • level
  • Able was I ere I saw Elba

反轉字元串與原字元串比較

反轉字元串或數字,并将反轉的字元串或數字與原始值進行比較。

package com.yuzhou1su.RelearnJava.Util;

public class palindrome {

    public static void main(String[] args) {
  
      String str = "level", reverseStr = "";
      
      int strLength = str.length();
  
      for (int i = (strLength - 1); i >=0; --i) {
        reverseStr = reverseStr + str.charAt(i);
      }
  
      if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
        System.out.println(str + " is a Palindrome String.");
      }
      else {
        System.out.println(str + " is not a Palindrome String.");
      }
    }
}
      

雙指針

package com.yuzhou1su.RelearnJava.Util;

public class palindrome {

    public static void main(String[] args) {
  
      String str = "level";
      char[] strArray = str.toCharArray();
      
      if (isPalindrom(strArray)) {
          System.out.println(str + " is a Palindrome String.");
      } else {
          System.out.println(str + " is not a Palindrome String.");
      } 
    }
    
    public static boolean isPalindrom(char[] word){
        int i1 = 0;
        int i2 = word.length - 1;
        while (i2 > i1) {
            if (word[i1] != word[i2]) {
                return false;
            }
            ++i1;
            --i2;
        }
        return true;
    }
}
      

Python中讨巧解法

def isPalindrome(self, x: int) -> bool:
    return str(x)==str(x)[::-1]