目前我有一个36000字的清单。我有一个进程将它们全部设置为小写(简单并且花费不到一秒)然后我决定使用一个代码来检查这些单词是否是另一个的字谜。
我使用此片段检查它们是否是字谜:
bool is_anagram(string s1, string s2) {
string c1(s1), c2(s2);
if(c1.length() != c2.length())
return 0;
sort(c1.begin(), c1.end());
sort(c2.begin(), c2.end());
return c1 == c2;
}
现在使用该代码我将代码分为两个容器。一个用于字谜,另一个用于非字谜。请注意,因为我不想重复我使用set而不是vector。 这是排序功能:
template<typename Container>
void sort_anagrams ( Container& unsorted, Container& yes, Container& no ) {
for( auto x : unsorted ) {
for ( auto y : unsorted ) {
if ( is_anagram ( x, y ) && y != x ) {
cout << "yes "<< x << " " << y << endl;
yes.insert(y);
}else {
cout << "no "<< x << " " << y << endl;
no.insert(y);
}
}
}
}
这是主要的,以防有人想要使用这个明显的“坏”代码:
int main() {
set<string> initial;
set<string> anagrams;
set<string> trash;
string input;
string newline = "\n";
ofstream os("output.txt", ios::out | ios::trunc | ios::binary);
while(cin >> input) {
initial.insert(input);
}
sort_anagrams ( initial, anagrams, trash );
cout << "printing" << endl;
for ( auto x : anagrams ) {
cout << x << endl;
if(os.good()) {
os.write(x.c_str(), sizeof(char)*x.size() );
os.write(newline.c_str(), sizeof(char)*newline.size() );
}
}
return 1;
}
:Dr:我正在尝试运行一个我没有很好地优化的过程,并且它永远都是需要的。我知道有更好的方法来处理这个列表,但我想从中学到的是,当我运行此代码并以块为单位处理列表时,我是否能够打开此过程的多个版本。 例如,这是我的列表: {&gt; [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] []}
我想要学习的是像这样处理它:
{&gt; [] [] []&gt; [] [] []&gt; [] [] []&gt; [] [] []&gt; [] [] []&gt; [] [] []&gt; [] [] []}
是否存在这些问题?
答案 0 :(得分:2)
这应该非常有效(c ++ 11,c ++ 03将使用map&lt;&gt;并设置&lt;&gt;)。
不需要多线程,因为它不会添加任何性能。在访问集合映射时,线程需要相互阻塞。
编辑:更新以从stdin获取单词列表并仅将anagram列表发送到stdout
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
#include <algorithm>
std::unordered_map<std::string, std::unordered_set<std::string>> anagram_map;
using namespace std;
auto main() -> int
{
while (cin) {
string word;
cin >> word;
auto sorted = word;
sort(begin(sorted), end(sorted));
anagram_map[sorted].insert(word);
}
// now we have sets of distinct words indexed by sorted letters
for (const auto& map_entry : anagram_map)
{
const auto& anagrams = map_entry.second;
if (anagrams.size() > 1)
{
// this is the code path where we have anagrams for a set of letters
auto sep = "";
for (const auto& word : anagrams) {
cout << sep << word;
sep = " ";
}
cout << endl;
}
}
return 0;
}
使用示例(unix,在windows下非常相似):
$ cat > words.txt
boy yob head pane nape planet plate tape pate
<ctrl-d>
$ c++ -o anagram -std=c++11 -stdlib=libc++ anagram.cpp
... or if you are using gcc ...
$ g++ -o anagram -std=c++11 anagram.cpp
$ ./anagram < words.txt > anagrams.txt
$ cat anagrams.txt
pate tape
nape pane
yob boy
答案 1 :(得分:0)
计算字符而不是排序字符串可以提高is_anagram()
从O(NlogN)到O(N)的性能:
bool is_anagram(string s1, string s2) {
if (s1.size() != s2.size()) return false;
int count1[256] = {0};
int count2[256] = {0};
int i;
for (i = 0; s1[i] && s2[i]; i++) {
count1[s1[i]]++;
count2[s2[i]]++;
}
for (i = 0; i < 256; i++)
if (count1[i] != count2[i])
return false;
return true;
}