C3L-UVa401-Palindromes

平台:

UVa Online Judge

題號:

401 - Palindromes

題目連結:

https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=6&page=show_problem&problem=342

題目說明:

输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含数字0。所谓回文串,就是反转以后和原串相同,如abba和madam。所有镜像串,就是左右镜像之后和原串相同,如2S和3AIAE。注意,并不是每个字符在镜像之后都能得到一个合法字符。在本题中,每个字符的镜像如下图所示(空白项表示该字符镜像后不能得到一个合法字符)。

输入的每行包含一个字符串(保证只有上述字符。不含空白字符),判断它是否为回文串和镜像串(共4种组合)。每组数据之后输出一个空行。

範例輸入:

NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA

範例輸出:

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

解題方法:

 首尾对比,判断是不是回文,镜像。

用常量数组按照字典序存储镜像字符。然后通过第几个( ch - 'A' || ch - '1' + 26 )直接调取。

 

程式碼:

 1 #include <iostream>
 2 #include <string>
 3 #include <cctype>
 4 
 5 using namespace std;
 6 
 7 const string msg[] = {
 8     "is not a palindrome.\n",
 9     "is a regular palindrome.\n",
10     "is a mirrored string.\n",
11     "is a mirrored palindrome.\n",
12 };
13 
14 const char rev[] = {
15     "A   3  HIL JM O   2TUVWXY51SE Z  8 "
16 };
17 
18 char getRev(char c) {
19     if (isalpha(c)) {
20         return rev[c - 'A'];
21     }
22     return rev[c - '1' + 26];
23 }
24 
25 int main() {
26     string str;
27     while (cin >> str) {
28         int pal = 1, mir = 1;
29         int len = str.size();
30         for (int i = 0; i < (len + 1) / 2; i++) {
31             if (str[i] != getRev(str[len - 1 - i])) {
32                 mir = 0;
33             }
34             if (str[i] != str[len - 1 - i]) {
35                 pal = 0;
36             }
37         }
38         cout << str << " -- " << msg[mir * 2 + pal] << endl;
39     }
40     return 0;
41 }
 

猜你喜欢

转载自www.cnblogs.com/lemonforce/p/13200111.html