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

  • 判断是否回文字符串
  • 方法一:传统两个指针 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!");
                }
        }
    }
    }



版权声明:本文为qq_33608638原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。