Careercup - Facebook面试题 - 5733320654585856

2014-05-02 09:59

题目链接

原题:

Group Anagrams 

input = ["star, astr, car, rac, st"] 

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

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

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

代码:

 1 // http://www.careercup.com/question?id=5733320654585856

 2 #include <algorithm>

 3 #include <iostream>

 4 #include <string>

 5 #include <vector>

 6 using namespace std;

 7 

 8 string ss1, ss2;

 9 bool comparator(const string &s1, const string &s2)

10 {

11     ss1 = s1;

12     ss2 = s2;

13     

14     sort(ss1.begin(), ss1.end());

15     sort(ss2.begin(), ss2.end());

16     

17     return ss1 < ss2;

18 }

19 

20 int main()

21 {

22     int i;

23     int n;

24     vector<string> v;

25     

26     while (cin >> n && n > 0) {

27         v.resize(n);

28         for (i = 0; i < n; ++i) {

29             cin >> v[i];

30         }

31         sort(v.begin(), v.end(), comparator);

32         cout << "{" << endl;

33         for (i = 0; i < (int)v.size(); ++i) {

34             cout << "    " << v[i] << endl;

35         }

36         cout << "}" << endl;

37         v.clear();

38     }

39     

40     return 0;

41 }

 

你可能感兴趣的:(Facebook)