Skip to content

Commit 59a7607

Browse files
committed
use regex for Valid Palindrome
1 parent 82f9399 commit 59a7607

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

Java/Valid Palindrome.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,28 @@ Hide Similar Problems (E) Palindrome Linked List
2525
2626
2727
*/
28-
28+
/*
29+
recap:
30+
Use regular expression [^a-zA-Z0-9] to replace all non-alphanumeric chars with ""
31+
*/
32+
public class Solution {
33+
public boolean isPalindrome(String s) {
34+
if (s == null || s.length() <= 1) {
35+
return true;
36+
}
37+
final String str = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
38+
int start = 0;
39+
int end = str.length() - 1;
40+
while (start < end) {
41+
if (str.charAt(start) != str.charAt(end)) {
42+
return false;
43+
}
44+
start++;
45+
end--;
46+
}
47+
return true;
48+
}
49+
}
2950

3051
/*
3152
3.4.2016 recap

0 commit comments

Comments
 (0)