字串计算

题目描述

给出一个01字符串(长度不超过100),求其每一个子串出现的次数。

输入描述:

输入包含多行,每行一个字符串。

输出描述:

对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
示例1

输入

复制
10101

输出

复制
0 2
01 2
1 3
10 2
101 2
/*给出一个01字符串(长度不超过100),求其每一个子串出现的次数。*/
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
    string str;
    map<string , int> mapstr;//试用map,本身已经用字典序排序
    string substring;
    while(cin>>str)
    {
        int len = str.length();
        mapstr.clear();      //清空mapstr
        for(int i=0;i<len;i++)
        {
            substring="";
            /*单个0或1*/
            substring+=str[i];
            if(mapstr.find(substring)!=mapstr.end())
            {
                mapstr[substring]++;
            }
            else{
                mapstr[substring] = 1;
            }
            /*从当前位置往后找其子串*/
            for(int j=i+1;j<len;j++)
            {
                substring+=str[j];
                if(mapstr.find(substring)!=mapstr.end())
                {
                    mapstr[substring]++;//匹配
                }
                else{
                    mapstr[substring] = 1;
                }
            }
        }
        //输出
        for(map<string,int>::iterator it=mapstr.begin();it!=mapstr.end();it++)
        {
            if(it->second>1)
            {
                cout<<it->first<<" "<<it->second<<endl;
            }
            
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/ttzz/p/10330638.html