Featured image of post 判断回文串和镜像串

判断回文串和镜像串

输入一个字符串(输入字符保证不含有数字 0),判断它是否为回文串或者镜像串,以下为回文串和镜像串的定义:

  • 回文串:反转后和原串相同。如 abba 和 madam。
  • 镜像串:串水平镜像后和原串相同。如 2S 和 3AIA。注意并不是所有字符镜像后都能得到一个合法字符。

输入的每行是一个字符串(只由 A~Z 或 1~9 组成),判断字符串是否为回文串和镜像串。每组数据之后输出一个空行。

样例输入

NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA

样例输出

NOTAPALINDROME — is not a palindrome.
ISAPALINILAPASI — is a regular palindrome.
2A3MEAS — is a mirrored string.
ATOYOTA — is a mirrored palindrome.

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>
#define maxn 100
using namespace std;
char s[maxn];
const char* mirror = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";
const char* msg[] = { "not a palindrome", "a regular palindrome", "a mirrored string", "a mirrored palindrome" };
char getMirrored(char ch) {
  if (isalpha(ch)) return mirror[ch - 'A'];
  else return mirror[ch - '0' + 25];
}
int main() {
  while (cin >> s) {
    int pFlag = 1, mFlag = 1;
    for (int i = 0; i < (strlen(s) + 1) / 2; i++) {
      if (s[i] != s[strlen(s) - 1 - i]) pFlag = 0;  // 不是回文串
      if (getMirrored(s[i]) != s[strlen(s) - 1 - i]) mFlag = 0;  // 不是镜像串
    }
    cout << s << " -- is " << msg[2 * mFlag + pFlag] << ".\n" << endl;
  }
  system("pause");
  return 0;
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Site built with Hugo, hosted by Firebase.
Theme Stack designed by Jimmy.