2014年4月25日 星期五

[LeetCode] Valid Palindrome

Problem:
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:O(n)
public class Solution {
    public boolean isPalindrome(String s) {
        String str = s.toLowerCase().replaceAll("[^a-zA-Z0-9]","");
     for(int i=0; i<str.length()/2;i++){
         if(str.charAt(i) != str.charAt(str.length()-1-i))
             return false;
     }
     return true;
    }
}

沒有留言:

張貼留言