题解 | #统计回文#
统计回文
https://www.nowcoder.com/practice/9d1559511b3849deaa71b576fa7009dc
import java.util.Scanner; //思路: (1)找到合适位置进行插入 // (2)判断字符串是不是回文串 public class Main { // 方法一:写个方法判断字符串是否为回文串 /** public static boolean isLegal(StringBuilder str) { for (int i = 0, j = str.length() - 1; i < j; i++, j--) { if (str.charAt(i) != str.charAt(j)) { return false; } } return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { StringBuilder A = new StringBuilder(in.nextLine()); StringBuilder B = new StringBuilder(in.nextLine()); int count = 0; for (int i = 0; i <= A.length(); i++) { StringBuilder tmp = new StringBuilder(A); tmp.insert(i, B); if(isLegal(tmp)){ count++; } } System.out.println(count); } } */ //方法二:将字符串翻转,看翻转后的字符串是不是和翻转前相同, //相同为回文串 public static void main(String[] args) { Scanner in = new Scanner (System.in); while (in.hasNext()) { StringBuffer A = new StringBuffer(in.nextLine()); StringBuffer B = new StringBuffer(in.nextLine()); int count = 0; for (int i = 0; i <= A.length(); i++) { //复制A,因为每次插入都会破坏字符串 StringBuffer tmp = new StringBuffer(A); tmp.insert(i,B); //准备字符串ret ,用来存放字符串翻转后的结果。 StringBuffer ret = new StringBuffer(tmp); ret.reverse(); if (ret.toString().equals(tmp.toString())) { count++; } } System.out.println(count); } } }