Valid Palindrome

来源:互联网 发布:淘宝店铺怎么改名字啊 编辑:程序博客网 时间:2024/05/16 23:37

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.
题目的意思是判断一个字符串是否为回文字符串,并且只考虑字母和数字和忽略大小写
思路:用两个指针,一个在前一个在后,遇到的字符非字母或者数字的时候就跳过,直到找到的字符是数字或者字母,比较前后两个字符,如果不等就直接返回false,如果相等就继续往下找。

注意: 空串默认是一个有效的回文字符串

public class Solution {    public boolean isPalindrome(String s) {          if(s.isEmpty()) return true;            int length=s.length();         int i=0;         int j=length-1;         while(i<=j)         {             if(!isalphanumeric(s.charAt(i))) i++;             else if(!isalphanumeric(s.charAt(j))) j--;             else if(!isQueal(s.charAt(i),s.charAt(j)))              {                return false;             }else if(isQueal(s.charAt(i),s.charAt(j)))             {                i++;                j--;             }         }         return true;    }     public  boolean isalphanumeric(char c)      {         return  (c<='Z' && c>='A')||(c<='z' && c>='a')||(c<='9' && c>='0');     }     public  boolean isQueal(char a,char b)     {         if((a<='z' && a>='a') && (b<='z' && b>='a'))             return a==b;         if((a<='Z' && a>='A') && (b<='z' && b>='a'))             return (a+32)==b;         if((a<='z' && a>='a') && (b<='Z' && b>='A'))             return (b+32)==a;         return a==b;     }}
0 0
原创粉丝点击