题目描述
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入描述:
输入包含多行,每行一个字符串。
输出描述:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
示例1
输入
10101
输出
0 2
01 2
1 3
10 2
101 2
题目解析:可以使用string的substr截取字符串,或者创建一个新的字符串记录。按字典排序,使用map进行计数。
代码:
#include <stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<iomanip>
using namespace std;
int main() {
string str;
map<string,int> mp;
while(cin >> str){
//两个for循环,截取了所有出现的子串样式
for(int i = 1 ;i <= str.size(); i++){
for(int j = 0; j < i; j++){
string sub_str = str.substr(j , i-j);
mp[sub_str]++;
}
}
map<string,int>::iterator it = mp.begin();
for(it ; it != mp.end() ; it++){
if(it->second > 1){
cout << it->first << " " << it->second << endl;
}
}
mp.clear();
}
return 0;
}
/*
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main(){
map<string,int> mp;
string str;
while(cin >> str){
for(int i = 0 ; i < str.size() ; i++){ //相当于下标
for(int j = i+1 ; j <= str.size(); j++){ //相当于长度
string s = str.substr(i, j-i);
mp[s]++;
}
}
map<string,int>::iterator it = mp.begin();
for(it ; it != mp.end() ; it++){
if(it->second > 1){
cout << it->first << " " << it->second << endl;
}
}
mp.clear();
}
return 0;
}
*/