验证是否回文

把相同的词汇或句子,调换位置或颠倒过来,产生首尾回环叫做回文

如“abba”、“abccba”、12321、123321是“回文”,“abcde”和“ababab”则不是“回文”。

以下核心代码help(s)的效率为O(m)

public class Palindrome {
     public static void main(String[] args) {
         String s = "A man, a plan, a canal: Panama";
         boolean b = isPalindrome(s);
         System.out.println(b);
     }

   public static String tool(String s ){

          s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

          return s;

   }
    public static boolean isPalindrome(String s){

           s = tool(s);
           return help(s);
     }

     private static boolean help(String s){
         int len = s.length();
         int index = 0;
         int m = len / 2;
         Stack<Character> stack = new Stack<Character>();
         while(index < m){
               stack.push(s.charAt(index));
              index++;
         }
        if(len % 2 == 1){
              index++;
        }
       while(index < len){
            if(stack.empty()){
                return false;
            }
              char a = stack.pop();
              if(a != s.charAt(index)){
               return false;
            }else{
                index++;
            }
        }
return true;

   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值