当前位置:网站首页>公里周日
公里周日
2022-08-09 09:58:00 【a waist-up rebel】
模式匹配算法c++实现
class Solution {
//sunday
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
unordered_map<char,int> shift;
for(int i = 0; i < m; ++i){
shift[needle[i]] = m - i;//How much computing in each character need to shift
}
int idx = 0,i = 0;
while(idx < n){
for(i = 0; i < m; ++i){
if(haystack[idx+i] != needle[i]){
break;
}
}
if(i == m) return idx;//匹配成功
if(idx+m>n) return -1;//防止越界
if(shift[haystack[idx+m]]){
//A term in the range before can move parts
idx += shift[haystack[idx+m]];
}else{
//After a is not within the scope of Give up the area directly
idx += m+1;
}
}
return -1;
}
};
class Solution {
//kmp
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
if (m == 0) {
return 0;
}
vector<int> pi(m);
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle[i] != needle[j]) {
j = pi[j - 1];
}
if (needle[i] == needle[j]) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = pi[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
};
class Solution {
//kmp
public:
void nextT(string &t, vector<int> &next,int n)
{
int j = 0, k = -1;
next[0] = -1;
while(j < n-1) {
if(k == -1 || t[j] == t[k]) {
next[++j] = ++k;
} else {
k = next[k];
}
}
}
int KMP(string &s, string &t)
{
int m = s.size();
int n = t.size();
int i = 0, j = 0;
vector<int> next(n);
nextT(t,next,n);
while(i < m && j < n) {
if(j == -1 || s[i] == t[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if(j == n)
return i - j;
return -1;
}
int strStr(string haystack, string needle)
{
return KMP(haystack,needle);
}
};
class Solution {
public://库函数
int strStr(string haystack, string needle)
{
return haystack.find(needle);
}
};
边栏推荐
猜你喜欢
STM32F103实现IAP在线升级应用程序
【个人学习总结】CRC校验原理及实现
Practical skills: a key for image information in the Harbor, quick query image
Ontology Development Diary 05-Strive to Understand SWRL (Part 2)
安装torch_sparse失败解决方法
快速解决MySQL插入中文数据时报错或乱码问题
JDBC中的增删改查操作
【ASM】字节码操作 MethodVisitor 案例实战 生成对象
EndNote使用指南
[Machine Learning] Detailed explanation of web crawler combat
随机推荐
Browser error classification
【个人学习总结】CRC校验原理及实现
时间复杂度和空间复杂度
Arrays类、冒泡排序、选择排序、插入排序、稀疏数组!
MySQ事务控制语言-TCL,进来学习!
try catch 对性能影响
MySQL全文索引
EndNote使用指南
Firebase+Facebook 授权 web 登录提示域名验证或跳转错误
7.FileFilter interface
latex中复杂公式换行等号对齐
元组 字典 集合
The GNU Privacy Guard
socket实现TCP/IP通信
7.Collections工具类
6.File类
MySQL约束关系,你必须要知道的知识点!
Celebrate ranked 18
日期操作比较全面得代码
梦笔记0809