0
点赞
收藏
分享

微信扫一扫

【串】字符串匹配 Brute-Force C++

吴wuwu 2022-04-14 阅读 31

串 字符串匹配 Brute-Force C++

  • s1=“helloyouoo” s2=“you”
  • s1从i=0开始,s2从j=0开始
  • 当发现s1[i]==s2[j]时,继续进行匹配i++ j++;当发现不相等时,i退回到刚开始寻找的下一个位置,j又从头开始找j=0
#include <bits/stdc++.h>
using namespace std; 
int main()
{
	//字符串匹配
	string s1="helloyouoo",s2="you";
	int i=0;
	int j=0;
	while(i<s1.length() && j<s2.length()){
		if(s1[i]==s2[j]){
			i++;
			j++;
		}else {
			i=i-j+1;
			j=0;
		}
	} 
	//j退出时,需满足j>=s2.length() 
	if(j==s2.length()){
		cout<<i<<endl;
	}else {
		cout<<"-1"<<endl;
	}
	return 0;
}
举报

相关推荐

0 条评论