《Cracking the Coding Interview》——第11章:排序和搜索——题目2
2014-03-21 20:55
393 查看
2014-03-21 20:49
题目:设计一种排序算法,使得anagram排在一起。
解法:自定义一个comparator,使用额外的空间来统计字母个数,然后比较字母个数。
代码:
题目:设计一种排序算法,使得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; }
相关文章推荐
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目1
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目8
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目3
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目4
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目5
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目6
- 《Cracking the Coding Interview》——第16章:线程与锁——题目3
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- 《Cracking the Coding Interview》——第18章:难题——题目13
- 《Cracking the Coding Interview》——第4章:树和图——题目5
- 《Cracking the Coding Interview》——第6章:智力题——题目3
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目5
- 程序员面试题目:Cracking the coding interview 分析与解答
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目2
- 《Cracking the Coding Interview》——第13章:C和C++——题目9
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- 《Cracking the Coding Interview》——第6章:智力题——题目4
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目6