您的位置:首页 > 其它

《Cracking the Coding Interview》——第11章:排序和搜索——题目2

2014-03-21 20:55 393 查看
2014-03-21 20:49

题目:设计一种排序算法,使得anagram排在一起。

解法:自定义一个comparator,使用额外的空间来统计字母个数,然后比较字母个数。

代码:

// 11.2 Sort an array of strings such that anagrams stay next to each other.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

string ta, tb;
int counting[256];

void countingSort(string &s)
{
int i, j;

for (i = 0; i < 256; ++i) {
counting[i] = 0;
}
for (i = 0; i < (int)s.length(); ++i) {
++counting[s[i]];
}
s.clear();

for (i = 0; i < 256; ++i) {
for (j = 0; j < counting[i]; ++j) {
s.push_back(i);
}
}
}

bool anagramComparator(const string &a, const string &b)
{
ta = a;
tb = b;
sort(ta.begin(), ta.end());
sort(tb.begin(), tb.end());

return ta < tb;
}

int main()
{
vector<string> v;
int i;
int n;

while (cin >> n && n > 0) {
v.resize(n);
for (i = 0; i < n; ++i) {
cin >> v[i];
}
sort(v.begin(), v.end(), anagramComparator);
for (i = 0; i < n; ++i) {
if (i > 0) {
cout << ' ';
}
cout << v[i];
}
cout << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐