[leetcode]125.Valid Palindrome
题目
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
解法
思路
思路很简单,设立两个指针,i从左往右,j从右往左,如果i和j所指的字符不是数字或字母,则继续往右或往左走,如果i和j所指的都为字母,那么比较i和j所指的字符都转为小写,然后判断是否相等即可。
代码
class Solution {
public boolean isPalindrome(String s) {
char[] c = s.toCharArray();
for(int i = 0, j = c.length - 1; i < j;) {
if(!Character.isLetterOrDigit(c[i])) i++;
else if(!Character.isLetterOrDigit(c[j])) j--;
else if(Character.toLowerCase(c[i++]) != Character.toLowerCase(c[j--]))
return false;
}
return true;
}
}
知识点总结
小写a到z的ASCII范围为 97到122
大写A到Z的ASCII范围为 65到90