Description
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
Example 1:
1 2
| Input: "A man, a plan, a canal: Panama" Output: true
|
Example 2:
1 2
| Input: "race a car" Output: false
|
Solution
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
| class Solution { public boolean isPalindrome(String s) { if (s.isEmpty()) { return true; } int head = 0, tail = s.length() - 1; char cHead, cTail; while(head <= tail) { cHead = s.charAt(head); cTail = s.charAt(tail); if (!Character.isLetterOrDigit(cHead)) { head++; } else if(!Character.isLetterOrDigit(cTail)) { tail--; } else { if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) { return false; } head++; tail--; } } return true; } }
|