美文网首页
lint0415 Valid Palindrome

lint0415 Valid Palindrome

作者: 日光降临 | 来源:发表于2019-02-07 16:07 被阅读0次

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.只考虑字母数字,并忽略大小写

    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.

    Example
    "A man, a plan, a canal: Panama" is a palindrome.

    "race a car" is not a palindrome.

    Challenge
    O(n) time without extra memory.

    keyword: 双指针
    方法一:
    100% test cases passedTotal runtime 180 ms
    Your submission beats 96.20% Submissions!

    public class Solution {
        public boolean isPalindrome(String s) {
            int len=s.length();
            char lft;
            char rht;
            if(len==0)
                return true;
            int lo=0;
            int hi=len-1;
            while(lo<hi){
                lft=s.charAt(lo);
                rht=s.charAt(hi);
                if(lft<'0' || (lft>'9' && lft<'A') || (lft>'Z' && lft<'a') || lft>'z'){
                    lo++;
                    continue;
                }
                if(rht<'0' || (rht>'9' && rht<'A') || (rht>'Z' && rht<'a') || rht>'z'){
                    hi--;
                    continue;
                }
                if(lft==rht || lft==rht+'a'-'A' || lft==rht-'a'+'A'){
                    lo++;
                    hi--;
                }else{
                    return false;
                }
            }
            return true;
        }
    }
    

    方法二:利用Java库函数
    toLowerCase(), Character.isLetterOrDigit()

    100% test cases passedTotal runtime 184 ms
    Your submission beats 66.60% Submissions!

    public class Solution {
        public boolean isPalindrome(String s) {
            int len=s.length();
            char lft;
            char rht;
            if(len==0)
                return true;
            int lo=0;
            int hi=len-1;
            s=s.toLowerCase();
            while(lo<hi){
                lft=s.charAt(lo);
                rht=s.charAt(hi);
                if(!Character.isLetterOrDigit(lft)){
                    lo++;
                    continue;
                }
                if(!Character.isLetterOrDigit(rht)){
                    hi--;
                    continue;
                }
                if(lft==rht){
                    lo++;
                    hi--;
                }else{
                    return false;
                }
            }
            return true;
        }
    }
    

    相关文章

      网友评论

          本文标题:lint0415 Valid Palindrome

          本文链接:https://www.haomeiwen.com/subject/snfgsqtx.html