卖萌的弱渣

I am stupid, I am hungry.

Valid Palindrome

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

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

  • 只考虑数字和字符
(Valid-Palindrome.py) download
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
27
28
29
class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True
        s = s.lower()
        l = 0
        r = len(s)-1
        alpha = "0123456789abcdefghijklmnopqrstuvwxyz"
        while l<r:
            while l < r and s[l] not in alpha:
                l += 1
            if l >= r:
                return True

            while l<r and s[r] not in alpha:
                r -= 1

            if l == r:
                return True

            if s[l] != s[r]:
                return False
            l += 1
            r -= 1
        return True
  • Java:
(Valid-Palindrome.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null)
            return true;

        int l = 0;
        int r = s.length()-1;
        while (l < r){
            while ((l < r) && !(Character.isLetterOrDigit(s.charAt(l))))
                l += 1;
            while ((l < r) && !(Character.isLetterOrDigit(s.charAt(r))))
                r -= 1;
            if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r)))
                return false;
            l += 1;
            r -= 1;
        }
        return true;
    }
}