题解 | #字符串字符匹配#
字符串字符匹配
http://www.nowcoder.com/practice/22fdeb9610ef426f9505e3ab60164c93
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1,str2;
bool hs;
while(cin>>str1>>str2){
int i=0,j=0;
while(i<str1.size()&&j<str2.size()){
if(str2[j]==str1[i]){
hs=true;
i++;
j=0;
}
else{
hs=false;
j++;
}
}
if(hs==true){
cout<<"true";
}
else{
cout<<"false";
}
}
}
这题要求判断短字符串中每个字符是否在长字符串中出现过,可以用暴力遍历两个字符串,但是这样实践按复杂度是O(mn)。我的思路是定义一个布尔值hs,然后用双指针分别指向两个字符串左端,如果当前字符相等则hs为真,短字符串的指针右移,长字符串从左端开始;若当前字符不相等,则判断hs为假,长字符串的指针右移。最后在根据hs的布尔值判断输出true or false,比循环遍历的好处在于当有一个字符没出现时直接跳出循环,可以判断为false。