版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82876222
Description:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
题意:判断一个字符串是否是回文,忽略除字母外的其他字符,并且对大小写不敏感;
解法:可以从字符串的首尾处开始向中间遍历,找到出现的字母或者数字,判断两个字符是否相等;
Java
class Solution {
public boolean isPalindrome(String s) {
int st = 0;
int ed = s.length() - 1;
s = s.toLowerCase();
while (st < ed) {
while (st < s.length() && !Character.isLetterOrDigit(s.charAt(st))) st++;
while (ed >= 0 && !Character.isLetterOrDigit(s.charAt(ed))) ed--;
if (st >= ed) break;
if (s.charAt(st) != s.charAt(ed)) return false;
st++;
ed--;
}
return true;
}
}