【LeetCode】125. Valid Palindrome
Difficulty:easy
More:【目錄】LeetCode Java實現
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 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
Intuition
Use two pointers, one points to head (walk toward tail), another points to tail(walk toward head), if two characters are different, then return false.
Be careful: There are no different between a lower case letter and its upper case in this problem.
Solution
With the help of API:
public boolean isPalindrome(String s) { if(s==null || s.length()<0) return false; int head=0; int tail=s.length()-1; while(head<=tail){ if(!Character.isLetterOrDigit(s.charAt(head))) head++; else if(!Character.isLetterOrDigit(s.charAt(tail))) tail--; else{ if(Character.toLowerCase(s.charAt(head))!=Character.toLowerCase(s.charAt(tail))) return false; head++; tail--; } } return true; }
Without API:
public boolean isPalindrome(String s) { if(s==null) return false; int i=0; int j=s.length()-1; while(i<=j){ while(i<s.length() && (!(isAlpha(s.charAt(i)) || isNumeric(s.charAt(i))))) i++; while(j>=0 && (!(isAlpha(s.charAt(j)) || isNumeric(s.charAt(j))))) j--; if(i<s.length() && j>=0 && !isSame(s.charAt(i),s.charAt(j)) ) return false; i++; j--; } return true; } private boolean isAlpha(char c){ if( (c>=‘a‘ && c<=‘z‘) || (c>=‘A‘ && c<=‘Z‘)) return true; return false; } private boolean isNumeric(char c){ if(c>=‘0‘ && c<=‘9‘) return true; return false; } private boolean isSame(char a,char b){ if(a==b) return true; int len=‘A‘-‘a‘; if((isAlpha(a)&&isAlpha(b)) && (a-b==len || b-a==len)) return true; return false; }
Complexity
Time complexity : O(n)
Space complexity : O(1)
What I‘ve learned
1. API: Character.isLetterOrDigit(c), Character.toLowerCase(c), Character.toUpperCase(c)
2. DO NOT forget head++ and tail-- in the line 14 and line 15
3. DO NOT forget i<s.length() && j>=
0
in the lines 8,10,12
4. s.length() not s.length
More:【目錄】LeetCode Java實現
【LeetCode】125. Valid Palindrome