Description

输入两个字符串,验证其中一个串是否为另一个串的子串。

Input

两行,每行一个字符串。

Output

若第一个串 s1​ 是第二个串 s2​ 的子串,则输出(s1) is substring of (s2)

否则,若第二个串 s2​ 是第一个串 s1​ 的子串,输出(s2) is substring of (s1)

否则,输出 No substring

Sample 1

Inputcopy Outputcopy
abc
dddncabca
abc is substring of dddncabca

Sample 2

Inputcopy Outputcopy
aaa
bbb
No substring

Hint

对于 100%100% 的数据,字符串长度在 2020 以内。

方法1

#include<bits/stdc++.h>
using namespace std;
string a,b;
int main()
{
    cin>>a>>b;
    if(a.find(b)!=a.npos)    //如果b是a的子串 
    {
        cout<<b<<" is substring of "<<a<<endl;
    }
    else if(b.find(a)!=b.npos)   //如果a是b的子串 
    {
        cout<<a<<" is substring of "<<b<<endl;
    }
    else      //如果没有子串关系 
    {
        cout<<"No substring"<<endl;
    }
    return 0;
}

方法2

#include<bits/stdc++.h>    //有测试用例未过,未查出来
using namespace std;

void scmp(string m,string n)
{
    int i = 1,j = 1;
    if(m.length() > n.length()) //m是主串,n是子串
    {
        while(i < m.length() && j < n.length())
        {
            if(m[i] == n[j])
            {
                i++;
                j++;
            }
            else
            {
                i = i-j+2;//回退
                j = 1;
            }
        }
        if(j >= n.length())//如果子串遍历完
        {
            cout << n <<" is substring of "<< m;
        }
        else
        {
            cout << "No substring";
        }
    }
    else
    {
        while(i < m.length() && j < n.length())//n是主串,m是子串
        {
            if(m[i] == n[j])
            {
                i++;
                j++;
            }
            else
            {
                j = j-i+2;
                i = 1;
            }
        }
        if(i >= m.length())
        {
            cout << m <<" is substring of "<< n;
        }
        else
        {
            cout << "No substring";
        }
    }
}

int main()
{
    string s1,s2;
    cin >> s1;
    cin >> s2;
    scmp(s1,s2);
    return 0;
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐