题目:
思路很简单:直接从字符串首尾遍历,判断是否相等
代码如下:
package cn.palindrome;
/**
* @program: algorithm_learn
* @description: 验证回文串
* @author: Mr.Luo
* @create: 2020-06-10 12:42
*/
public class Solution_2 {
public static boolean isPalindRome(String s){
if (s == ""){
return true;
}
int l = 0;
int r = s.length() - 1;
//从字符串头和尾向中间遍历
while (l < r){
if (!Character.isLetterOrDigit(s.charAt(l))){//字符不是数字和字母的情况
l++;
}else if (!Character.isLetterOrDigit(s.charAt(r))){//字符不是数字和字母的情况
r--;
}else {
//判断两者是否相等
if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))){
return false;
}
l++;
r--;
}
}
return true;
}
public static void main(String[] args) {
// String s = "abC,ddcba";
String s = "A man, a plan, a canal: Panama";
String s2 = "race a car";
System.out.println(isPalindRome(s));
System.out.println(isPalindRome(s2));
}
}