暴力遍历方法
#include<bits/stdc++.h>
using namespace std;
// 给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
struct node {
string sub;
int count;
node(string str, int a):sub(str), count(a){
}
};
bool cmpUp(node a, node b) {
return a.sub.compare(b.sub)< 0;
}
int main() {
string str;
vector<node> list;
while(cin>> str) {
list.clear();
int n= str.length();
for(int i=0; i<n; i++) {
for(int len=1; len<n-i+1; len++) {
string sub= str.substr(i, len);
int count= 0;
for(int k=0; k<n-len+1; k++) {
if(sub.compare(str.substr(k, len))== 0) {
count++;
}
}
// cout<< sub<< " count:"<< count<< endl;
if(count> 1) {
int exit= 0;
for(int i=0; i<list.size(); i++) {
if(list[i].sub.compare(sub)== 0) {
exit= 1;
break;
}
}
if(!exit) {
list.push_back(node(sub, count));
}
}
}
}
sort(list.begin(), list.end(), cmpUp);
for(int i=0; i<list.size(); i++) {
cout<< list[i].sub<< " "<< list[i].count<< endl;
}
}
return 0;
}

京公网安备 11010502036488号