leetcode 28.实现strStr()
题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
解法 KMP
构建一个状态转换表.
next数组太难理解了。采用leetcode上labuladong大佬的思路。用更容易的状态转换表来表示。
//KMP
class Solution {public:int strStr(string haystack, string needle) {int s_len = needle.length();int d_len = haystack.length();if(s_len == 0)return 0;if(d_len == 0)return -1;vector<vector<int>> dp(s_len + 1,vector<int> (128,0));dp[0][needle[0]] = 1;int X = 0; //X为影子状态,比i慢一步启动。for(int i = 1; i < s_len ;i++){for(int j = 0; j < 128 ; j++)dp[i][j] = dp[X][j];dp[i][needle[i]] = i + 1;X = dp[X][needle[i]];}int st = 0;for(int i = 0; i < d_len;i++){st = dp[st][haystack[i]];if(st == s_len)return i - s_len + 1;}return -1;}
};
leetcode 28.实现strStr()相关推荐
- 【To Do】LeetCode 28. Implement strStr() 和KMP算法
LeetCode 28. Implement strStr() Solution1:我的答案 有投机取巧之嫌啊~ 注意string中的查找函数在查找时 参考网址:https://www.cnblogs ...
- LeetCode - 28. Implement strStr()
28. Implement strStr() Problem's Link -------------------------------------------------------------- ...
- leetCode 28. Implement strStr() 字符串
28. Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in ha ...
- strstr函数_[LeetCode] 28. 实现strStr()
题目链接: https://leetcode-cn.com/problems/implement-strstr/ 题目描述 实现 strStr() 函数. 给定一个 haystack 字符串和一个 n ...
- LeetCode 28. 实现strStr()
实现 strStr() 函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始).如果不存在,则返 ...
- [leetcode] 28. Implement strStr() 解题报告
题目链接:https://leetcode.com/problems/implement-strstr/ Implement strStr(). Returns the index of the fi ...
- leetcode 28. Implement strStr() 实现strStr()
C++代码,题目相对不是很难 1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 if(need ...
- LeetCode 28 实现 strStr()
https://leetcode-cn.com/problems/implement-strstr/ 解决方案 class Solution {public int strStr(String hay ...
- Leetcode 28. 实现 strStr()
原题链接 解:KMP算法 class Solution { public:int strStr(string s, string p) {if (p.empty()) return 0;int n = ...
最新文章
- 我对序列化(Serializable)的理解
- ValueStack基础:OGNL
- python反转一个整数、123变成321_python整数反转算法
- SparkSQL-从0到1认识Catalyst
- thymeleaf 判断checkbox是否选中_一日看尽长安花——复选框(CheckBox)数据清洗和统计的SAS实现...
- C语言int的字节数跟什么有关,C语言中int型字长和什么有关
- MediaInfo源代码分析 5:JPEG解析代码分析
- python读取中文txt操作 转化为拼音
- python 参数带星号_python 函数参数的传递(参数带星号的说明)
- PHP查询函数调用堆栈
- 热点:安全问题是否能将DNS推入云服务
- javax.persistence.TransactionRequiredException: No transactional EntityManager available
- Centos7部署kubernetes集群CA证书创建和分发(二)
- phpstudy 本地配置url重写
- RT-Thread:STM32F407虚拟U盘,无法识别拔出问题解决方案
- Libgdx Box2D实战---放开那小球(二:Box2D介绍)
- 11 Daemonset:忠实可靠的看门狗
- 中关村十大AI研究院|盘点
- 源代码转换:Tangible Software Solutions v22.10.20
- java 开发微型公众账号应用