Uva 401 回文串镜像串傻傻分不清
紫薯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
Re:从零开始的刷题生活 文章被收录于专栏
一起来重刷题叭~ 由于精力有限,题意只说大概,题目细节可以点击vjudge链接查看。 题目以紫薯中的Uva例题/习题为主,有时候有些比较经典的算法也会特意从其它OJ上找题,并不一定出现在紫薯上。 噢,紫薯指——《算法竞赛入门经典(第2版)》by 刘汝佳 喜欢的小伙伴点个赞呗?不然我只能认为一直只有我一个人在自娱自乐orz....