leetcode_Valid Palindrome

来源:互联网 发布:苹果的gsx查询软件 编辑:程序博客网 时间:2024/05/07 14:04

描述:

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.

思路:

很简单,搞一个while循环即可,比较前后的字符是否相同,直至start>=end

代码:

 String str=null;    public boolean isPalindrome(String s) {        boolean isPali=true;        str=s;        int i=0,j=s.length()-1;        while(i<j)        {            while(i<j&&!isLegal(getChar(i)))                i++;            while(i<j&&!isLegal(getChar(j)))                j--;            if(i<j)            {                 if(getChar(i)!=getChar(j))                {                     isPali=false;                     break;                }            }            i++;            j--;        }        return isPali;    }    public char getChar(int index)    {        char ch=str.charAt(index);        if(ch>='A'&&ch<='Z')            ch+='a'-'A';        return ch;    }    public boolean isLegal(char ch)    {        if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||(ch>='0'&&ch<='9'))            return true;        return false;    }


0 0
原创粉丝点击