lint0415 Valid Palindrome

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,672评论 0 10
  • 女孩趴在徐涛的肩膀上抽抽嗒嗒的哭,细柔的长发轻轻的拂过徐涛的手臂,痒痒的掻动着,让人心悬意马,他不由自主的搂住那还...
    酷雪冰凌阅读 8,195评论 5 5
  • 在16年底的时候,我申请到了台湾铭传大学访学的名额。台湾的访学项目只有一个学期的时间,所以现在我已经回来了。现在看...
    安大心阅读 269评论 0 1
  • 逗比到处有,朋友圈里尤其多。 有朋友总结了朋友圈里的十种神经病,将自拍、求赞、拉票、微商等十种行为当做难以忍受的神...
    郁文堂阅读 691评论 2 1
  • 奇葩转变到王又美又凶真想把名字改成转变大王!他的眼睛像一个透明的宝石亮闪闪的流露出神秘的光芒,鼻子挺挺的像一个小矮...
    陈靖文爸爸阅读 322评论 1 0

友情链接更多精彩内容