a812簡單反向比較與部分鏡射映射
CPE:Palindromes (UVa 401)
獨立判斷一般迴文與鏡像性質,組合四種輸出。
解題思路
一般迴文檢查 s[i]=s[n−1−i]。鏡像字串則檢查 mirror[s[i]]=s[n−1−i],映射表只填題目列出的字元,雙向配對都要建立,例如 E→3 與 3→E。沒有映射的字元會讓鏡像性質失敗。
兩個布林值必須獨立計算,因為鏡像字串不一定是一般迴文,例如 E3。中央字元也需檢查:奇數長度的中間字元必須能映射回自己。最後依兩個性質選四種固定文字,原字串照印,每筆後再輸出空白行。輸入只用 O 而不用 0,不需額外替換。
Step-by-step animation
示意:E3
步驟 1 / 3
一般迴文
左 E 與右 3 不同,一般迴文失敗。
E
3
- palindrome
- 0
#include <iostream>
#include <string>
using namespace std;
int main() {
string from = "AEHIJLMOSTUVWXYZ12358", to = "A3HILJMO2TUVWXY51SEZ8";
char mirror[256] = {};
for (int i = 0; i < int(from.size()); ++i)
mirror[(unsigned char)from[i]] = to[i];
string s;
while (cin >> s) {
bool pal = true, mir = true;
for (int i = 0; i < int(s.size()); ++i) {
char other = s[s.size() - 1 - i];
if (s[i] != other)
pal = false;
if (mirror[(unsigned char)s[i]] != other)
mir = false;
}
string kind = mir ? (pal ? "a mirrored palindrome" : "a mirrored string")
: (pal ? "a regular palindrome" : "not a palindrome");
cout << s << " -- is " << kind << ".\n\n";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。