Valid Palindrome
Two pointers
A pointer moves from start to end, the other moves from end to start. The characters they points to should be the same.
Note: In this problem, chars other than [A-Za-z0-9]
should be ignored.
Source code Read on Github
1 public class Solution {
2
3 boolean valid(char[] chars, int i){
4 return !(('A' <= chars[i] && chars[i]<= 'Z')
5 || ('a' <= chars[i] && chars[i]<= 'z')
6 || ('0' <= chars[i] && chars[i]<= '9'));
7 }
8
9 public boolean isPalindrome(String s) {
10 if(s == null) return false;
11
12 char[] chars = s.toLowerCase().toCharArray();
13 int i = 0, j = chars.length - 1;
14
15 while(i < j){
16
17 // ignore space etc.
18 while( (i < j) && valid(chars, i)) i++;
19 while( (i < j) && valid(chars, j)) j--;
20
21 if(chars[i] != chars[j]) return false;
22
23 i++;
24 j--;
25 }
26
27 return true;
28 }
29 }