链接:
http://ac.jobdu.com/problem.php?pid=1149
题目描述:
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入:
输入包含多行,每行一个字符串。
输出:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
思路:
只有100个数,可以遍历一遍(O(N^2))找到所有的字串,然后把它们都放到map里,map存储的顺序就是字典序,所以直接再从里边拿出来就可以了。
需要注意的地方就是,map遍历需要用到迭代器,对map这个STL还是需要熟悉。
输出的时候,用printf就是乱码,用cout就很正常,我觉得又是和类型有关,还是cout智能。
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
map<string, int> str;
map<string, int>::iterator ite;
int main(){
string s;
while (cin >> s){
str.clear();
int len = s.length();
for (int i = 0; i < len; i++){
for (int j = i; j < len; j++){
string temp = s.substr(i, j - i + 1);
if (str.find(temp) == str.end()){
str[temp] = 1;
}
else{
str[temp] += 1;
}
}
}
ite = str.begin();
while (ite != str.end()){
if (ite->second > 1){
cout << ite->first << " " << ite->second << endl;
//printf("%s %d\n", ite->first, ite->second);
}
ite++;
}
}
return 0;
}