紫薯P48 例题3-3
一、题意
输入一些字符串,要求分别对每个字符串判断:是不是回文串;是不是镜像串。并输出相应的答句。
二、解析
回文串判断:reverse后是否相等
镜像串判断:reverse+映射每个字符到其镜像字符后,是否和原串相等
三、代码
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
const string reverses = "A 3 HIL JM O 2TUVWXY51SE Z 8 ";
const string ans[4] = {"is not a palindrome.", "is a regular palindrome.",
"is a mirrored string.", "is a mirrored palindrome."};
// idx = 2 * x + y. x表示是否是镜像, y表示是否是回文
int main() {
string str;
while(cin >> str) {
bool x = 0, y = 0;
string rev = str;
reverse(rev.begin(), rev.end());
y = str == rev;
string mir;
for(auto ch : rev) {
int idx = characters.find(ch);
mir.push_back(reverses[idx]);
}
x = str == mir;
cout << str << " -- " << ans[2 * x + y] << "\n" << endl;
}
}四、归纳
- 在时间复杂度允许下,学会用两个const串表示映射关系,而不一定要用map或其它函数
- 有同学可能会说,遍历一半就可以判断了,然而遍历一半并不会在数量级上减少时间复杂度,因此应该怎么方便怎么来就好啦
看了一下我第一次做时写的代码...真认真啊orz

京公网安备 11010502036488号