当前位置: 首页 > article >正文

1140:验证子串--next.data()、KMP和find

1140:验证子串--KMP

    • 题目
  • 解析
    • next.data()
    • KMP代码
    • Find代码

题目

在这里插入图片描述

解析

对于字符串的匹配常见的KMP算法【面试常考】

KMP中需要注意的是:应该从下标1开始遍历,因为下标0前面无值,不能匹配next
固在循环外应初始next[0]=0;//易忘点

next[0]=0;//易错点
//i需从1开始遍历,因为下标0前面无值,不能匹配next
	for(int i=1;i<s.size();i++)

便于使用的find代码也在下面了

next.data()

next.data()是std::vector容器的一个成员函数,它的作用是获取底层数组的首地址

vector<int> next(10); // 创建一个有10个int的数组
int* ptr = next.data(); // 获取底层数组的首地址

KMP代码

#include <iostream>
#include <vector>
#include<set>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <climits>  // 包含INT_MAX常量
#include <cctype>
#include<map>
using namespace std;

void getNext(string s,int *next){
	int j=0;
	next[0]=0;
//i需从1开始遍历,因为下标0前面无值,不能匹配next
	for(int i=1;i<s.size();i++){
		while(j>0&&s[i]!=s[j]) j=next[j-1];
		if(s[i]==s[j]) j++;
		next[i]=j;
	}
}

bool check(string s1,string s2){
	if(s2.size()==0) return true;
	vector<int>next(s2.size());
	getNext(s2,next.data());
	int j=0;
	for(int i=0;i<s1.size();i++){
		while(j>0&&s1[i]!=s2[j]) j=next[j-1];
		if(s1[i]==s2[j]) j++;
		if(j==s2.size()) return true;
	}
	return false;
}
int main(){
	string s1,s2;
	cin>>s1>>s2;
	if(check(s2,s1)){
		cout<<s1 << " is substring of " << s2 << endl;
		return 0;
	}
	if(check(s1,s2)){
		cout<< s2 << " is substring of " << s1 << endl;
		return 0;
	}
	cout<<"No substring" << endl;
return 0;
}

Find代码

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
const int N = 1e2 + 10;
int a[N];
int cnt;
int main()
{
	string s1, s2;
	cin >> s1 >> s2;
	if (s1.length() > s2.length())
	{
		if (s1.find(s2) != -1)
			cout << s2 << " is substring of " << s1;
		else
			cout << "No substring";
	}

//这里的else覆盖率长度相等的情况
	else
		if (s2.find(s1) != -1)
			cout << s1 << " is substring of " << s2;
	else
			cout << "No substring";
}

http://www.kler.cn/a/588566.html

相关文章:

  • 大模型-提示词调优
  • 查询修改ORACLE的server、客户端和导出dmp文件 字符集编码
  • LeetCode--198. 打家劫舍【从返回最大值到输出路径】
  • 【Go语言圣经2.4】
  • 以太坊生态中有代币标准和协议,针对不同场景设计了丰富的功能
  • 网络安全演练有哪些形式
  • GO语言的GC(垃圾回收)原理
  • 浏览器缓存机制:JavaScript 文件缓存导致 404 错误的解决方案
  • HTML5与CSS3新特性详解
  • vue父组件向子组件传函数,子组件调用函数向父组件传参
  • 【CXX】6.9 CxxVector<T> — std::vector<T>
  • Linux内核传输层UDP源码分析
  • 日志、类加载器、XML(配置文件)
  • 【HarmonyOS NEXT】实现文字环绕动态文本效果
  • JS基础部分
  • DeepSeek在学术写作选择研究方向的2个核心提示词
  • pip install和conda install的区别
  • C# --- LINQ
  • 没有公网服务器的情况下,建立反弹 Shell
  • 网络编程、URI和URL的区别、TCP/IP协议、IP和端口、URLConnection