给出一个只包含0和1的字符串(长度在1到100之间),求其每一个子串出现的次数。
10101
0 2 01 2 1 3 10 2 101 2
1 #include<iostream> 2 #include<map> 3 #include<vector> 4 using namespace std; 5 map<string, int>m; 6 int main(){ 7 string a; 8 cin>>a; 9 int i, j; 10 for(i = 0; i < a.length(); i++){ 11 for(j = 1; j+i <= a.length(); j++){ 12 string ss = a.substr(i,j); 13 m[ss]++; 14 } 15 } 16 map<string, int>::iterator it = m.begin(); 17 for(it = m.begin(); it!=m.end(); it++){ 18 if(it->second<=1) continue; 19 cout<<it->first<<" "<<it->second<<endl; 20 } 21 return 0; 22 }
备注:枚举就行了。关键是我对map和string的用法都有点陌生了……我看的一个代码还写了个string数组用来记录子串,但其实完全没必要。
要注意的就是map的迭代器的用法,别忘了orz
还有substr的第一个参数是起点,第二个参数是长度,而用j来枚举长度要注意j最小是1,而最大j+i是可以达到a.length()的
原文:https://www.cnblogs.com/fangziyuan/p/13113923.html