zoukankan      html  css  js  c++  java
  • 统计回文

    题目描述

    “回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。花花非常喜欢这种拥有对称美的回文串,生日的时候她得到两个礼物分别是字符串A和字符串B。现在她非常好奇有没有办法将字符串B插入字符串A使产生的字符串是一个回文串。你接受花花的请求,帮助她寻找有多少种插入办法可以使新串是一个回文串。如果字符串B插入的位置不同就考虑为不一样的办法。
    例如:
    A = “aba”,B = “b”。这里有4种把B插入A的办法:
    * 在A的第一个字母之前: "baba" 不是回文 
    * 在第一个字母‘a’之后: "abba" 是回文 
    * 在字母‘b’之后: "abba" 是回文 
    * 在第二个字母'a'之后 "abab" 不是回文 
    所以满足条件的答案为2

    输入描述:

    每组输入数据共两行。
    第一行为字符串A
    第二行为字符串B
    字符串长度均小于100且只包含小写字母

    输出描述:

    输出一个数字,表示把字符串B插入字符串A之后构成一个回文串的方法数
    示例1

    输入

    aba
    b

    输出

    2
     1 import java.util.Scanner;
     2 
     3 /**
     4  *
     5  * 回文 
     6  * 直接计算求最小
     7  * @author Dell
     8  *
     9  */
    10 public class Main {
    11 static public int count = 0;
    12 static public String aString="aba" ;
    13 static public String bString="b" ;
    14 // 判断是否回文
    15 static public boolean isOK(StringBuilder s) {
    16 //     .reverse()
    17 //    Causes this character sequence to be replaced by the reverse of the sequence.
    18 //  先做备份 在取倒序   使用 String 来避免 引用传递问题
    19     String s1 =new String(s);
    20     String s2 = new String(s.reverse());
    21         // 正反相反就是回文
    22     if (s1.equals(s2)) {
    23         return true;
    24     }else {
    25         return false;
    26     }
    27 }
    28 static public void f() {
    29     for (int i = 0; i <=aString.length(); i++) {
    30         StringBuilder sb = new StringBuilder(aString);
    31          sb = sb.insert(i, bString);    
    32         boolean is = isOK(sb);    
    33         if (is) {
    34             count++;
    35         }
    36     }
    37 }
    38 public static void main(String[] args) {
    39  Scanner in = new Scanner(System.in);
    40     aString = in.nextLine();
    41     bString = in.nextLine();
    42     f();
    43     System.out.println(count);
    44 }
    45 }
  • 相关阅读:
    策略模式Strategy
    flex项目
    模板方法Template Method
    timer与ScheduledExecutorService
    java两个字符串的相似度
    一个简单的webshell
    状态模式State
    Java性能优化
    责任链模式China of Responsibility
    ns2.34下mflood协议的完美移植
  • 原文地址:https://www.cnblogs.com/the-wang/p/8979376.html
Copyright © 2011-2022 走看看