28.implement-str-str 实现strStr()
2022/8/15 23:27:18
本文主要是介绍28.implement-str-str 实现strStr(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
KMP算法
关键在于如何求next数组
void getNext(int *next, const string &s) { int j = -1; next[0] = j; for (int i = 1; i < s.size(); i++) { // next[j + 1]指向匹配好的前缀的下一个字符 // i指向后缀末尾位置 while (j >= 0 && s[i] != s[j + 1]) { j = next[j]; } if (s[i] == s[j + 1]) { j++;//j+1表示最长相等子串的长度,所以字符相等时,长度递增 } next[i] = j; } }
完整代码
#include <string> using std::string; class Solution { public: void getNext(int *next, const string &s) { int j = -1; next[0] = j; for (int i = 1; i < s.size(); i++) { // next[j + 1]指向匹配好的前缀的下一个字符 // i指向后缀末尾位置 while (j >= 0 && s[i] != s[j + 1]) { j = next[j]; } if (s[i] == s[j + 1]) { j++; } next[i] = j; } } int strStr(string haystack, string needle) { if (needle.size() == 0) return 0; int next[needle.size()]; getNext(next, needle); int j = -1; for (int i = 0; i < haystack.size(); i++) { //出现不等时,跳到最长相等子串的下一个字符处 while (j >= 0 && haystack[i] != needle[j + 1]) { j = next[j]; } if (haystack[i] == needle[j + 1]) { j++; } if (j == (needle.size() - 1)) return i - needle.size() + 1; } return -1; } };
这篇关于28.implement-str-str 实现strStr()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?