字符串穷举算法(STL)

这里实现的功能是给出一个任意序列的字符串组合,程序会产生包含所有字符的组合,算法部分用到了C++ STL中的next_permutation()函数,并计算耗时(用到了Win32 API)。代码很简单,就不加注释了....

 

1 #include <iostream>
2 #include <string>
3 #include <algorithm>
4 #include <windows.h>
5  using namespace std;
6
7  int main()
8 {
9 string letters;
10 cout<<">>>>> Enter the STRING to TEST: (quit to quit):";
11
12 while (cin>>letters && letters!="quit")
13 {
14 SYSTEMTIME _time1,_time2;
15 float interval;
16 GetLocalTime(&_time1);
17
18 cout<<"Permutations of"<<letters<<endl;
19 sort(letters.begin(),letters.end());
20 cout<<letters<<endl;
21 double count=1;
22
23 while(next_permutation(letters.begin(),letters.end()))
24 {
25 cout<<letters<<endl;
26 ++count;
27 }
28
29 cout<<">>>>> The aumount:"<<count<<endl;
30 cout<<endl;
31
32 GetLocalTime(&_time2);
33 interval=(_time2.wMinute-_time1.wMinute)*60;
34 interval+=_time2.wSecond-_time1.wSecond;
35 interval*=1000;
36 interval+=(_time2.wMilliseconds-_time1.wMilliseconds);
37 interval/=1000;
38
39 printf(">>>>>耗时: %f 秒\n",interval );
40 cout<<endl;
41 cout<<">>>>> Enter next STRING to TEST (quit to quit):";
42 }
43 system("pause");
44 return 0;
45 }
46  

 

当输入12345678 程序运行效果如下:

 


 

posted on 2010-09-10 15:56  hicjiajia  阅读(881)  评论(1编辑  收藏  举报