如何生成给定长度的词典字符串?
我正在寻找一种算法来生成长度为N的字符串(词典顺序),按字典顺序排列。例如,给定长度为1,生成的字符串为:“a”,“b”,“c”,“d”,“e”,“f”,g,h,i,j,k ...,z
对于长度为2,生成的字符串应为:“aa”,“ab”,“ac”,“ad”,...,“ba”,“bb”,...,“zz”。< / p>
我们怎么能这样做?
这就是我所做的:
void permute(string a, int i, int n, int length)
{
int j;
if (i == length){
string cand = a.substr(0,length);
cout<<cand<<endl;
}
else
{
for (j = i; j <= n; j++)
{
swap((a[i]), (a[j]));
permute(a, i+1,n,length);
swap((a[i]), (a[j]));
}
}
}
在调用“permute(a,0,a.size(),1)”时,字符串a看起来像这样:
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffgggggggggggggggggggghhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrssssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzz
生成正确的输出,但它重复了字典字符串。如果我把它简化为字母表,我相信像“aa”,“aaaa”这样的字符串会被遗漏。那么我们怎么能解决这个问题呢?
答案 0 :(得分:7)
我会对一个简单地循环遍历字母表的函数进行递归调用,并为每个字母放置调用它。
初步测试表明这可行:
#include <iostream>
#include <sstream>
#include <string>
void addLetters(std::string base, int tgt_depth)
{
if (base.length() == tgt_depth) {
std::cout << base << std::endl;
return;
}
for (char letter = 'a'; letter <= 'z'; ++letter) {
std::stringstream ss;
ss << letter;
addLetters(base + ss.str(), tgt_depth);
}
}
int main(int argc, char* argv)
{
// first argument is your "base" -- start with nothing
// second argument is the depth to which to recurse, i.e. how many letters
addLetters("", 2);
}
答案 1 :(得分:1)
假设您想要查看这些字符串的字典顺序中的哪个字符串M,请在基数26中表示此数字,然后将0映射到a,1到b,依此类推。您必须向左添加零(或a-s),直到字符串达到所需长度。现在解决你的问题只需遍历整数(最多为长度为N的字符串数为26 N )并应用我建议的转换。
答案 2 :(得分:0)
for(i='a';i<='z';i++)
{
recur(new String(i));
}
void recur(String s)
{
if(s.length()==dig)
{
add s to array
return
}
for(i='a';i<='z';i++)
recur(s+i);
}
虽然这段代码不足以产生超过5位数,因为有26个挖掘的可能性。我不知道c ++所以我写了算法。但是我觉得编码器里面没有任何语言可以转换