回文,英文 palindrome,如果该字符串的反转与原始字符串相同,则该字符串称为回文字符串。 比如: radar level Able was I ere I saw Elba 反转字符串与原字符串比较 反转字符串或数字,并将反
回文,英文 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.");
}
}
}
输出结果:level is 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]