如果两个单词,他们的字母组成一样而字母位置有区别,那么就称这两个单词为变位词。如 pans 和 span , tops 和 stop。
所有的变位词,对他们按字母顺序排序,得到相同的字符串(这个字符串成为该单词的签名)。把这个字符串作为这堆单词的排序标准,排序完之后,相同签名的单词肯定是相邻位置,如果当前单词的签名和上一个单词的签名相同,则他们是变位词,在同一行输出,否则不是,另外一行输出。
sign.exe 读入每个单词,为每个单词生成签名
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string sig;
string word;
while(cin>>word)
{
sig = word;
sort(sig.begin() , sig.end());
cout<<sig<<" "<<word<<endl;
}
return 0;
}
然后用sort对每一行排序,对于签名相同的单词,在同一行输出
squash.exe 读入签名和该单词,如果签名和之前相同,则直接输出,否则换行
#include <iostream>
#include <string>
using namespace std;
#define STRLEN 30
int main()
{
string sig,word;
string oldSig("");
bool bIsFirst = true;
while(cin>>sig && cin>>word)
{
if (sig != oldSig && !bIsFirst)
{
cout<<endl;
}
oldSig = sig;
cout<<word<<" ";
bIsFirst = false;
}
return 0;
}
写1.txt
pans
pots
opt
snap
stop
tops
sign < 1.txt | sort | squash > 2.txt
得到结果
2.txt
pans snap
pots stop tops
opt