Careercup - Facebook面试题 - 5733320654585856

时间:2021-01-15 14:46:31

2014-05-02 09:59

题目链接

原题:

Group Anagrams
input = ["star, astr, car, rac, st"]
output = [["star, astr"],["car","rac"],["st"]);

题目:给定一堆字符串,设法把anagram都排在一起。

解法:自定义一个comparator,互为anagram的两个字符串在排好序以后是相同的。根据这个规则可以写出个效率不怎么高,但是代码很短的算法。

代码:

 // http://www.careercup.com/question?id=5733320654585856
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std; string ss1, ss2;
bool comparator(const string &s1, const string &s2)
{
ss1 = s1;
ss2 = s2; sort(ss1.begin(), ss1.end());
sort(ss2.begin(), ss2.end()); return ss1 < ss2;
} int main()
{
int i;
int n;
vector<string> v; while (cin >> n && n > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
}
sort(v.begin(), v.end(), comparator);
cout << "{" << endl;
for (i = ; i < (int)v.size(); ++i) {
cout << " " << v[i] << endl;
}
cout << "}" << endl;
v.clear();
} return ;
}