首页 > 代码库 > 回文词
回文词
题目来自于张汝佳的《算法竞赛入门经典(第二版)》
题目描述:
输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含数字0。所谓回文串,就是反转以后跟原串相同,如 abba 和 madam。所有镜像串,就是左右镜像之后和原串相同,如 2s 和 3AIAE。注意,并不是每个字符在镜像之后都能得到一个合法字符。在本题中,每个字符的镜像如图所示
输入的每行包含一个字符串(保证只有上述字符,不含空白字符),判断它是否为回文串和镜像串(共四种组合)。每组数据之后输出一个空行。
样例输入:
NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA
样例输出:
NOTAPALINDROME -- is not a palindrome.
ISAPALINILAPASI -- is a regular palindrome.
2A3MEAS -- is a mirrored string.
ATOYOTA -- is a mirrored palindrome.
我的代码:
#include<iostream> #include<cstring> #include<ctype.h> using namespace std; int main() { char a[100], chat[]="A 3 HIL J O 2TUVWX51SE Z 8 "; int i, j, note = 0, no = 0; while (cin >> a) { note = 0; for (i = 0; i < strlen(a) / 2; i++) { if (a[i] == a[strlen(a) - 1 - i]) { if (isalpha(a[i]) && chat[a[i] - 65] != a[strlen(a) - 1 - i]) { no = 1; break; } } if (a[i] != a[strlen(a) - 1 - i]) { if (isalpha(a[i]) && chat[a[i] - 65] != a[strlen(a) - 1 - i]) { no = 1; break; } note = 1; break; } } if (note == 0 && no == 0) { cout << a << "-- is a mirrored palindrome.\n"; continue; } if (note == 1) { cout << a << " -- is not a palindrome.\n"; continue; } if (note == 0) { cout << a << " -- is a regular palindrome.\n"; continue; } if (no == 0) { cout << a << "-- is a mirrored string.\n"; continue; } if (no == 1) { cout << a << "-- is not a mirrored string.\n"; continue; } } return 0; }
答案的代码:
#include<stdio.h> #include<string.h> #include<ctype.h> const char* rev = "A 3 HIL J O 2TUVWX51SE 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 (scanf("%s", s) == 1) { int len = strlen(s); int p = 1, m = 1; for (int i = 0; i < (len + 1) / 2; i++) { if (s[i] != s[len - 1 - i])p = 0; if (r(s[i]) != s[len - 1 - i]) m = 0; } printf("%s -- is %s.\n\n", s, msg[m * 2 + p]); } return 0; }
回文词
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。