Different substrings [Blue Bridge Cup 2019 Preliminary]

Topic link: Time limit for different substrings
: 1 Sec Memory limit: 256 MB

Title description:
A non-empty substring of a string refers to a string of consecutive characters with a length of at least 1 in the string.
For example, the string aaab has non-empty substrings a, b, aa, ab, aaa, aab, aaab, a total of 7 substrings.
Note that when calculating, only count the number of strings that are essentially different.
Excuse me, how many different non-empty substrings are there in the string 0100110001010001?

The meaning of the question: is to figure out how many non-empty substrings there are in this string.
Idea: This kind of fill-in-the-blank question, after we run the result, comment out the code and just print the running result.

Insert picture description here

Code:

string s;
cin>>s;
int len=s.length();
map<string,int> mp; // 存放截取出来的字符串
int num=0; // 累加不同子串的数量
for(int i=0; i<len; i++)
{
    
    
    for(int j=1; j<=len; j++)
    {
    
    
        string ss=s.substr(i,j); //从下标i开始截取长度为j的字符串
        if(mp[ss]==0)
        {
    
    
            num++;
            mp[ss]++;
        }
    }
}
cout<<num<<endl;

Operation result:
Insert picture description here
I will elaborate on the substr in the code, and understand
str = s.substr(index,length);

That is, from the index subscript of the s string (the subscript starts from 0), a substring of length length is intercepted and assigned to str.
Give a chestnut:

s = "abcdefg";
str = s.substr(index,length);
str = s.substr(2,3); // output: cde
str = s.substr(2); // output: cdefg

From the running result of the above code, we can see that the number of different non-empty substrings of this string is 100, so we can directly output 100.
In addition, please note that the question does not require input, so we only output the result.

Insert picture description here

Complete code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<iomanip>
using namespace std;
int main()
{
    
    
    /*string s;
    cin>>s;
    int len=s.length();
    map<string,int> mp; // 存放截取出来的字符串
    int num=0; // 累加不同子串的数量
    for(int i=0; i<len; i++)
    {
        for(int j=1; j<=len; j++)
        {
            string ss=s.substr(i,j); //从下标i开始截取长度为j的字符串
            if(mp[ss]==0)
            {
                num++;
                mp[ss]++;
            }
        }
    }
    cout<<num<<endl;
    */
    cout<<100<<endl; // 直接输出即可,代码注释掉
}

Don’t forget to like it after reading, thank you for your support!
Insert picture description here
Come on!

Work together!

Keafmd

Guess you like

Origin blog.csdn.net/weixin_43883917/article/details/108821624
Recommended