1.10 排列对称串
1.10 题目内容
字符串有些是对称的,有些是不对称的,请将那些对称的字符串按从小到大的顺序输出。字符串先以长度论大小,如果长度相同,再以 ASCII 码值为排序标准。
输入描述:输入数据中含有一些字符串(1≤串长≤256)。
输出描述:根据每个字符串,输出对称的那些串,并且要求按从小到大的顺序输出。
输入样例
123321
123454321
123
321
sdfsdfd
121212
\\dd\\
输出样例
123321
\\dd\\
123454321
#include <iostream>
#include <set>
#include<algorithm>
using namespace std;
struct Comp
{
bool operator()(const string &a,const string &b)
{
return (a.length()!=b.length()?a.length()<b.length():a<b);
}
};
int main(int argc, char* argv[])
{
multiset<string,Comp> ms;
string t,s;
while(cin>>s)
{
t=s;
reverse(t.begin(),t.end());
if(t==s)
{
ms.insert(s);
}
}
multiset<string,Comp>::iterator is;
for(is=ms.begin();is!=ms.end();is++)
{
cout<<*is<<endl;
}
return 0;
}
另解:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//自己设计排序比较函数
bool Comp(const string &s1,const string &s2)
{
return s1.length()!=s2.length()?s1.length()<s2.length():s1<s2;
}
int main(int argc, char* argv[])
{
vector<string>v;
string t,s;
while(cin>>s)
{
t=s;
//反转字符串,用来判断字符是否对称
reverse(t.begin(),t.end());
if(t==s)
{
v.push_back(s);
}
}
//按 Comp 函数比较规则排序
sort(v.begin(),v.end(),Comp);
//输出向量中的所有元素
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<endl;
}
return 0;
}