判断是否回文字符串 And 最长回文字符串 子串长度

本文介绍了两种判断字符串是否为回文串的方法:一种是使用双指针从两端向中间遍历比较;另一种是利用StringBuilder反转字符串后与原字符串进行对比。这两种方法简单高效,适用于多种编程任务。
  • 判断是否回文字符串
  • 方法一:传统两个指针 begin---end;  str.charAt(begin)==str.charAt(end) 不能用
    str[begin]==str[end];没有这种用法; String str 
  • import java.util.Scanner;  
    public class Main{  
      public static void main(String[] args){  
          Scanner sc = new Scanner(System.in);   
          while(sc.hasNext()){
              String str = sc.next();
              int begin = 0;int end = str.length()-1;
              while(begin < end){
                  if(str.charAt(begin)==str.charAt(end)){
                      begin++;end--;
                  }
                  else{
                      System.out.print("No!");
                      break;
                  }
              }
              if(begin>=end){
                  System.out.print("Yes!");
              }
          }
      }
    }

    方法二:
  •  StringBuilder sb=new StringBuilder(str); //注意数据结构
      String newStr = sb.reverse().toString();
  • 链接:https://www.nowcoder.com/questionTerminal/df00c27320b24278b9c25f6bb1e2f3b8
    来源:牛客网
    import java.util.Scanner;
    /**
    *回文串就是一串字符正反序一样,所以将原来的字符串倒叙以后和原先字符串匹配则就是回文串
    *字符串倒叙可直接用str.reverse()
    */
    public class Main {
      
        public static void main(String[] args) {
                Scanner scan=new Scanner(System.in);
                while(scan.hasNext()){
                String str=scan.nextLine();               
                StringBuilder sb=new StringBuilder(str); //注意数据结构
                String newStr = sb.reverse().toString();
                    
                if(str.equals(newStr)){
                    System.out.println("Yes!");
                }else{
                    System.out.println("No!");
                }
        }
    }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值