题解 | #子串计算#

子串计算

http://www.nowcoder.com/practice/bcad754c91a54994be31a239996e7c11

#include<iostream>
#include<map>
#include<string>
using namespace std;

int main(){
    map<string, int >myMap;
    string str;
    cin>>str;
    for(int i = 0; i < str.size(); i++){
        for(int j = i; j < str.size(); j++){
            myMap[str.substr(i,j-i+1)]++;
        }
    }
    for(map<string, int>::iterator it = myMap.begin(); it != myMap.end(); it++){
        if(it->second>1) cout<<it->first<<" "<<it->second<<endl;
    }
    return 0;
}

使用map来定义字符串到int的映射,int的初始值自动是0
遍历字符串的所有子串,然后利用map进行计数,最后输出即可。
要注意map底层使用红黑树来实现,所以map的排序刚好是按照string的字典序进行排序,和题目符合。

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:58
点赞 评论 收藏
分享
头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
21
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务