leetCode. isParlindrome

参考资料:左程云算法课
125. Valid Palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = “A man, a plan, a canal: Panama”
Output: true
Explanation: “amanaplanacanalpanama” is a palindrome.

class Solution {
// 方法1
    public boolean isPalindrome1(String s) {
        char[] str = s.toCharArray();
        StringBuilder builder = new StringBuilder();

        for(char ch:str)
        {
            if((ch>='0'&&ch<='9')||('a'<=ch&&ch<='z'))
            {
                builder.append(ch);
            }else if('A'<=ch&&ch<='Z')
            {
                builder.append((char)(ch-('A'-'a')));
            }
        }

        String s2 = builder.toString();
        return s2.equals(builder.reverse().toString());
    }



// 方法2: 双指针法
     public boolean isPalindrome(String s) {
     // two pointers
     char[] str = s.toCharArray();
     int L=0;
     int R = str.length-1;

     while(L<=R)
     {
         if(valid(str[L])&&valid(str[R]))
         {
             if(equal(str[L],str[R]))
             {
                 L++;
                 R--;
             }else{
                 return false;
             }
         }else{
             L+=valid(str[L])?0:1;
             R-=valid(str[R])?0:1;
         }
     }
    return true;
    }
     public boolean valid(char ch)
     {
         return isNume(ch)||isAlph(ch);
     }
     public boolean isNume(char ch)
     {
         return ch>='0' && ch<='9';
     }
     public boolean isAlph(char ch)
     {
         return (ch>='a' && ch<='z')||(ch>='A' && ch<='Z');
     }
     public boolean equal(char ch1, char ch2)
     {
         if(isNume(ch1)||isNume(ch2))
         {
             return ch1==ch2;
         }
         return ch1==ch2 || Math.max(ch1,ch2)-Math.min(ch1,ch2)==32;
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值