[leetcode] Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
https://oj.leetcode.com/problems/valid-palindrome/
思路:判断palindrome,双指针从两头向内判断即可。注意过滤掉其他字符。
public class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() == 0) return true; int i = 0; int j = s.length() - 1; while (i <= j) { while (i < s.length() && (!Character.isLetter(s.charAt(i)) && !Character.isDigit(s.charAt(i)))) i++; while (j >= 0 && (!Character.isLetter(s.charAt(j)) && !Character.isDigit(s.charAt(j)))) j--; if (i > j) break; if (Character.toUpperCase(s.charAt(i)) != Character.toUpperCase(s.charAt(j))) return false; i++; j--; } return true; } public static void main(String[] args) { System.out.println(new Solution().isPalindrome("abcaa")); } }
第二遍记录:
注意终止条件和过滤其他字符。