输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于10。*/
//好的思路,减去一个字母,判断是否为回文
public class addCharhuiwen { public static boolean isHuiWen(String s) { int n = s.length(); for (int i = 0; i < n / 2; i++) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String s = in.next(); if (isHuiWen(s) == true) System.out.println("YES"); else { if (s.length() % 2 == 0) {// 偶数位,添一个字母变成奇数个 考虑以中间偏左的点作为中心, // 比较俩侧的值,若有俩次不同,则不构成回文,一次不同可以 int lmid = s.length() / 2 - 1; int rmid = s.length() / 2; int flag = 0, flag2 = 0; for (int i = 0, k = 0; i < s.length() / 2;) {// 以中心左侧的点为轴 if (lmid - i - 1 < 0) break; if (lmid - i - 1 >= 0 && s.charAt(lmid - i - 1) == s.charAt(lmid + k + 1)) { i++; k++; continue; } else { flag++; k++; if (flag > 1) { flag = 2; break; } } } for (int i = 0, k = 0; i < s.length() / 2;) {// 以右侧点为轴 if (rmid + k + 1 >= s.length()) break; if (rmid + k + 1 < s.length() && s.charAt(rmid - i - 1) == s.charAt(rmid + k + 1)) { i++; k++; continue; } else { flag2++; i++; if (flag2 > 1) { flag2 = 2; break; } } } if (flag <= 1 || flag2 <= 1) { System.out.println("YES"); } else { System.out.println("NO"); } } else {// 奇数位 int flag = 0; int l = 0;// 左相等bccab int r = 0;// 右相等baccb boolean b = true; int mid = s.length() / 2; for (int i = 0, k = 0; i < s.length() / 2;) { if (mid - i - 1 < 0 || mid + k + 1 >= s.length()) { break; } if (mid - i - 1 >= 0 && s.charAt(mid - i - 1) == s.charAt(mid) && s.charAt(mid) == s.charAt(mid + k + 1)) {// baccccb的情况 i++; k++; } else { // 直到mid左右的值不等于mid的值 baccb的情况 // 这里只执行一次 if (b) { if (s.charAt(mid - i - 1) == s.charAt(mid)) {// 左边相等bccab i++; l = 1; } else if (s.charAt(mid + k + 1) == s.charAt(mid)) {// 右边相等baccb k++; r = 1; } else {// 不能成回文 flag = 2; break; } b = false; } } if (s.charAt(mid - i - 1) == s.charAt(mid + k + 1)) { i++; k++; } else { flag++; if (flag >= 2) break; if (l == 1) { k++; } if (r == 1) { i++; } } } if (flag <= 1) { System.out.println("YES"); } else { System.out.println("NO"); } } } } }// while in.hasNext() }