给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
思路:双指针
package edu.LeetCode;
/**
* 给定一个字符串,验证它是否是回文串
*/
public class 验证回文串 {
public static boolean isPalindrome(String s){
if(s == null || s.length() == 1){
return true;
}
String str = s.toLowerCase();//将给定的字符串转化成为小写的字母
int left = 0;
int right = str.length() - 1;
while(left < right) {
//如果left所指向的字符串不是字母或数字,则跳过
while (left < right && !isCheck(str.charAt(left)))
left++;
//如果right所指向的字符串不是字母或数字,则跳过
while (left < right && !isCheck(str.charAt(right)))
right--;
if (str.charAt(left) == str.charAt(right)) {
left++;
right--;
} else {
return false;
}
}
return true;
}
//检测字符串是否是数字和字母
public static boolean isCheck(char ch){
int a = (int)ch;
if(a >= 48 && a <= 57 || a >= 97 && a <= 122){
return true;
}else {
return false;
}
}
public static void main(String[] args) {
String str = ".,";
System.out.println(isPalindrome(str));
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。