Java 字符串回文判断:拆分、轴对称、翻转操作
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); scanner.nextLine(); // consume the newline character
for (int i = 0; i < T; i++) {
String str = scanner.nextLine();
boolean isPalindrome = isPalindromePossible(str);
if (isPalindrome) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
public static boolean isPalindromePossible(String str) {
StringBuilder sb = new StringBuilder(str);
// Split operation
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == 'w') {
sb.replace(i, i + 1, "vv");
i += 1;
} else if (c == 'm') {
sb.replace(i, i + 1, "nn");
i += 1;
}
}
// Axis symmetric operation
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == 'b') {
sb.replace(i, i + 1, "d");
} else if (c == 'd') {
sb.replace(i, i + 1, "b");
} else if (c == 'p') {
sb.replace(i, i + 1, "q");
} else if (c == 'q') {
sb.replace(i, i + 1, "p");
}
}
// Reverse operation
sb.reverse();
return sb.toString().equals(str);
}
}
原文地址: https://www.cveoy.top/t/topic/qoNz 著作权归作者所有。请勿转载和采集!