第三章
例题3-3 回文词(Palindromes)
输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含0。
代码
#include<iostream>
#include<string.h>
using namespace std;
//镜像字符表
const char* rev = "A 3 HIL JM O 2TUVWXY51SE Z 8 ";
char mirror(char a)
{
if (isalpha(a))
return rev[a - 'A'];
return rev[a - '0' + 25];
}
int main()
{
string str;
while (cin >> str)
{
bool p = true, m = true;
int length = str.length();
for (int i = 0; i < length; i++)
{
if (str[length - i - 1] != str[i])
p = false;
if (str[length - i - 1] != mirror(str[i]))
m = false;
}
if (p == false && m == false)
cout << str << " -- is not a palindrome";
else if (p == true && m == false)
cout << str << " -- is a regular palindrome";
else if (p == false && m == true)
cout << str << " -- is a mirrored string";
else if(p == true && m == true)
cout << str << " -- is a mirrored palindrome";
cout << endl;
}
return 0;
}
测试数据
input
NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA
output
NOTAPALINDROME – is not a palindrome
ISAPALINILAPASI – is a regular palindrome
2A3MEAS – is a mirrored string
ATOYOTA – is a mirrored palindrome
反思
- 一开始犯了一个最低级的错误,在判断的时候,下标为 length - i 的字符并不对应于下标为 i 的字符,相对应的字符下标应为 length - i - 1 。
- 关于输出,书上的代码更加简洁
const char* msg[] = {"not a palindrome", “a regular palindrome”,
"a mirrored string", "a mirrored palindrome"};
cout << str << " -- is " << msg[m * 2 + p] << endl;
//此处, m 和 p 为 int 型,有 0 和 1 两个值,分别对应 false 和 true