125.Valid Palindrome

Test cases

1
2
3
4
5
6
7
8
9
10
"0P"
"ab"
",."
",a,"
",aa."
""
"a"
"bab"
"baab"
"babb"

Solution 1: accepted 10ms

Two pointers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int l = 0;
int r = s.length() - 1;
while (l < r) {
char lc = s.charAt(l);
char rc = s.charAt(r);
if (lc < 48 || (57 < lc && lc < 97) || lc > 122) {
l++;
continue;
}
if (rc < 48 || (57 < rc && rc < 97) || rc > 122) {
r--;
continue;
}
if (lc != rc) {
System.out.println(lc + " " + rc);
return false;
} else {
l++;
r--;
}
}
if(l < r && s.charAt(l) != s.charAt(r)) // two left in the middle
return false;
return true;
}

Improved to 8ms using Character functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public boolean isPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
char lc = s.charAt(l);
char rc = s.charAt(r);
if (!Character.isLetterOrDigit(lc)) {
l++;
continue;
}
if (!Character.isLetterOrDigit(rc)) {
r--;
continue;
}
if (Character.toLowerCase(lc) != Character.toLowerCase(rc)) {
return false;
} else {
l++;
r--;
}
}
if(l < r && s.charAt(l) != s.charAt(r)) // two left in the middle
return false;
return true;
}