输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含数字0。所谓回文串,就是反转以后和原串相同,如abba和madam。所有镜像串,就是左右镜像之后和原串相同,如2S和3AIAE。注意,并不是每个字符在镜像之后都能得到一个合法字符。在本题中,每个字符的镜像如图3-3所示(空白项表示该字符镜像后不能得到一个合法字符)。
import java.util.Scanner;
public class Main {
private static final String REVERSE_PALINDROME_TABLE = "AAMMYYB0N0Z5C0OO11DOP02SE3Q03EF0R040G0S25ZHHTT60IIUU70JLVV88K0WW90LJXX";
public static void main(String[] args) {
solution();
}
public static void solution() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
classify(scanner.nextLine());
}
}
public static void classify(String str) {
boolean isPalindrome = isPalindrome(str);
boolean isMirror = isMirror(str);
if (isPalindrome && isMirror) {
System.out.printf("%s -- is a mirrored palindrome.\n\n", str);
} else if (isPalindrome) {
System.out.printf("%s -- is a regular palindrome.\n\n", str);
} else if (isMirror) {
System.out.printf("%s -- is a mirrored string.\n\n", str);
} else {
System.out.printf("%s -- is not a palindrome.\n\n", str);
}
}
public static boolean isPalindrome(String str) {
int length = str.length(); // real length
int range = length / 2; // range to check
for (int i = 0; i < range; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
return false;
}
}
return true;
}
public static boolean isMirror(String str) {
int length = str.length(); // real length
int range = length / 2; // range to check
for (int i = 0; i <= range; i++) {
char c = str.charAt(i);
char r = getReverseChar(c);
if (r != str.charAt(length - i - 1)) {
return false;
}
}
return true;
}
public static char getReverseChar(char c) {
int length = REVERSE_PALINDROME_TABLE.length() / 2;
for (int i = 0; i < length; i++) {
if (c == REVERSE_PALINDROME_TABLE.charAt(i * 2)) {
return REVERSE_PALINDROME_TABLE.charAt(i * 2 + 1);
}
}
return '0';
}
}