A24163. 验证子串
填空题
中等
知识点
题目描述
验证子串
题目描述
输入两个字符串,验证其中一个串是否为另一个串的子串。
输入
输入两个字符串, 每个字符串占一行,长度不超过200且不含空格。
输出
若第一个串s1是第二个串s2的子串,则输出(s1) is substring of (s2)
否则,若第二个串s2是第一个串s1的子串,输出(s2) is substring of (s1)
否则,输出 No substring。
输入样例
abc
dddncabca输出样例
abc is substring of dddncabca参考答案
#include<bits/stdc++.h>
using namespace std;
#define N 205
bool isSubStr(char s1[], char s2[])//枚举判断s2是不是s1的子串
{
int l1 = strlen(s1), l2 = strlen(s2);
for(int i = 0; i <= l1-l2; ++i)
{//判断s1从s1[i]~s1[i+l2-1]是否与s2相同
bool isSame = true;
for(int j = 0; j < l2; ++j)
{
if(s1[i+j] != s2[j])
{
isSame = false;
break;
}
}
if(isSame)
return true;
}
return false;
}
int main()
{
char s1[N], s2[N], t[N];
cin >> s1 >> s2;
int l1 = strlen(s1), l2 = strlen(s2);
if(l1 < l2)//保证s1更长
{
strcpy(t, s1);
strcpy(s1, s2);
strcpy(s2, t);
swap(l1, l2);
}
if(isSubStr(s1, s2))
cout << s2 << " is substring of " << s1;
else
cout << "No substring";
return 0;
}答案解析
#include<bits/stdc++.h>
using namespace std;
bool isSubStr(string s1, string s2)//s2是不是s1的子串
{
int l1 = s1.length(), l2 = s2.length();
for(int i = 0; i <= l1 - l2; ++i)
{
if(s1.substr(i, l2) == s2)
return true;
}
return false;
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
if(s1.length() < s2.length())
swap(s1, s2);
if(isSubStr(s1, s2))
cout << s2 << " is substring of " << s1;
else
cout << "No substring";
return 0;
}
上一题
下一题