总结:
思维易错:
题目其实并不是很复杂。容易观察到回文串的规律, 但是对于镜像串假设为len长,划分为两部分是[0, len/2)和[len/2, len).由于C++是向下取整,所以可能造成[0, len/2]比[len/2, len)少1。所以如果只判断一半的话,应该是[0, len / 2 + 1)或者[0, (len + 1) / 2);
相关API:
- C中判断类型的函数再cctype中。java中则是Character这个类的工具方法
- C中取字符串可以直接使用[]加索引。java适用charAt(index)
- C中定义产量使用const, java使用final。并且const在于指针前, 表示的是指针值不变。
//
// Created by sixleaves on 16/11/17.
//
#include
#include
#include
const char* reverseTable = "A 3 HIL JM O 2TUVWXY51SE Z 8 ";
const char* msg[] = {" -- is not a palindrome.", " -- is a regular palindrome.",
" -- is a mirrored string.", " -- is a mirrored palindrome."};
char reverseChar(char ch) {
if (isdigit(ch)) {
return reverseTable[ch - '1' + 26];
}
return reverseTable[ch - 'A'];
}
int main () {
char line[100] = {0};
while (scanf("%s", line) != EOF) {
int rM = 1, cP = 1;
int len = strlen(line);
for (int i = 0; i < (len + 1) / 2; i++) {
if (line[i] != line[len - 1 - i]) {
cP = 0;
}
if (reverseChar(line[i]) != line[len - 1 - i]) {
rM = 0;
}
}
printf("%s%s\n\n", line, msg[rM * 2 + cP]);
}
return 0;
}
package CH3.ArraryAndStrings;
import java.util.Scanner;
/**
* Created by sixleaves on 16/11/17.
*/
public class UVA401 {
static final String reverseTable = "A 3 HIL JM O 2TUVWXY51SE Z 8 ";
static public void main(String[] args) {
final String[] msg = new String[]{" -- is not a palindrome.", " -- is a regular palindrome.",
" -- is a mirrored string.", " -- is a mirrored palindrome."};
int rM, cP;
int kcase = 0;
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
rM = cP = 0;
String line = cin.nextLine();
int len = line.length();
cP = 1;
for (int i = 0; i < len / 2; i++) {
if (line.charAt(i) != line.charAt(len - 1 - i)) {
cP = 0;
break;
}
}
StringBuilder mirror = new StringBuilder();
for (int i = len -1; i >=0; i--) {
mirror.append(reverseChar(line.charAt(i)));
}
rM = 0;
if (mirror.toString().equals(line)) rM = 1;
System.out.println(line + msg[rM * 2 + cP]);
System.out.println();
}
}
static public char reverseChar(char ch) {
if (Character.isDigit(ch)) {
return reverseTable.charAt(ch - '1' + 26);
}
return reverseTable.charAt(ch - 'A');
}
}