题意:判断一个字符串中是否存在回文;英文回文的意思就是一个字符串从前往后和从后往前的字符串是一样的。
思路:直接搞两个index,一个从前往后,一个从后往前,看是否相等。
代码:
package ValidPalindrome;
public class ValidPalindrome {
public boolean IsPalindrome(String s) {
if(s.length()== 0) return true;
s = s.toUpperCase();
int low1 = 'A';
int high1 = 'Z';
int low2 = '0';
int high2 = '9';
int low = 0 ,high = s.length()-1;
while(low < high){
if((s.charAt(low)<low1 || s.charAt(low)>high1)
&& (s.charAt(low) < low2 || s.charAt(low) > high2)){
low++;
continue;
}
if((s.charAt(high)<low1 || s.charAt(high) > high1)
&& (s.charAt(high) < low2 || s.charAt(high) > high2)){
high--;
continue;
}
if(s.charAt(low) == s.charAt(high)){
low++;
high--;
}else
return false;
}
return true;
}
public static void main(String[] args) {
String string = "A man,a plan,a canal: anama";
ValidPalindrome vp = new ValidPalindrome();
System.out.println(vp.IsPalindrome(string));
}
}
本文介绍了一种用于判断字符串是否为回文的有效算法。通过双指针技术从前向后及从后向前遍历字符,忽略非字母数字字符,并将所有字母转换为大写进行比较。该方法能够高效地确定字符串是否满足回文条件。
1158

被折叠的 条评论
为什么被折叠?



