UVa 401-Palindromes

输入一个字符串,判断它是否属于回文串以及镜像串。输入不包含0以及空白字符。

#include <iostream>;
#include <string.h>
#include <ctype.h>
using namespace std;
const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";
const char* msg[] = { "not a palindrome","a regular palindrome","a mirrored string","a mirrored palindrome" };
char r(char ch) {
	if (isalpha(ch))
		return rev[ch - 'A'];
	return rev[ch - '0' + 25];
}
int main() {
	char s[30];
	while (cin >> s) {
		int len = strlen(s);
		int p = 1, m = 1;
		for (int i = 0; i < (len+1)/2; i++) {
			if (s[i] != s[len - i - 1]) p = 0;
			if (s[i] != r(s[len - 1 - i])) m = 0;
		}
		cout << s << "--- is " << msg[m * 2 + p]<<endl<<endl;
	}
	return 0;
}

使用常量数组往往能简化代码,是一个非常实用的方法。
本题代码中的msg数组的使用也值得学习。
ch-‘A’ 得到的是字母ch在字母表中的位置,ch-'0’得到的是数字ch本身。

发布了7 篇原创文章 · 获赞 0 · 访问量 53

猜你喜欢

转载自blog.csdn.net/qq_21606413/article/details/104847683