2015年5月27日星期三

Valid Palindrome leetcode

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.
从两边出发往中间走看是否匹配, 遇到不是字母或者数字的就跳过;
character 变为小写的格式为 c1 = (char) (c1 - 'A' + 'a'); 或者也可以直接 Character.toLowerCase(char)
时间复杂度是O(n),空间上是O(1)

public class Solution {
    public boolean isPalindrome(String s) {
        if (s.length() == 0|| s == null) {
            return true;
        }
        int start = 0;
        int end = s.length() - 1;
        while (start <= end) {
            if (!isValid(s.charAt(start))) {//这里用了if循环 因为如果是while left会溢出
                start++;
                continue;
            }
            if (!isValid(s.charAt(end))) {
                end--;
                continue;
            }
            if (isSame(s.charAt(start), s.charAt(end))) {
                start++;
                end--;
            } else {
                return false;
            }
        }
        return true;
    }
    public boolean isValid(char k) {
        if ((k >= 'a' && k <= 'z') || (k >= 'A' && k <= 'Z') || (k >= '0' && k <= '9')) {
            return true;
        }
        return false;
    }
    public boolean isSame(char c1, char c2) {
        if (c1 >= 'A' && c1 <= 'Z') {
            c1 = (char) (c1 - 'A' + 'a');
        }
        if (c2 >= 'A' && c2 <= 'Z') {
            c2 = (char) (c2 - 'A' + 'a');
        }
        return c1 == c2;
    }
}

没有评论:

发表评论