LeetCode - Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

Solution:

 1 public class Solution {

 2     public boolean isValid(char c){

 3         if(c >= 'a' && c <= 'z') return true;

 4         if(c >= '0' && c <= '9') return true;

 5         return false;

 6     }

 7     public boolean isPalindrome(String s) {

 8         // Start typing your Java solution below

 9         // DO NOT write main() function

10         if(s.equals("")) return true;

11         s = s.toLowerCase();

12         int len = s.length();

13         int left = 0, right = len - 1;

14         while(left < right){

15             while(!isValid(s.charAt(left))){

16                 left++;

17                 if(left >= right) return true;

18             } 

19             while(!isValid(s.charAt(right))){

20                 right--;

21                 if(left >= right) return true;

22             }

23             if(s.charAt(left) != s.charAt(right)) return false;

24             left++;

25             right--;

26         }

27         return true;

28     }

29 }

 

More strictly, 

 1 public class Solution {

 2     public boolean isPalindrome(String s) {

 3         // Start typing your Java solution below

 4         // DO NOT write main() function

 5         if(s.equals("")) return true;

 6         int len = s.length();

 7         for(int i = 0; i <= len / 2; i++) {

 8             if(s.charAt(i) != s.charAt(len - 1 - i))

 9                 return false;

10         }

11         return true;

12     }

13 }

 

 

你可能感兴趣的:(LeetCode)