LeetCode(28)Implement strStr()
来源:互联网 发布:删除数组中指定元素 c# 编辑:程序博客网 时间:2024/05/27 14:13
题目
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.
分析
这是一道模式匹配算法,给定两个字符串haystack与needle,给出needle在haystack完全匹配的首位置坐标(从0开始)。
这道题在数据结构中有讲解,除了开始的简单模式匹配算法BF算法,还给出了改进后的KMP经典算法,下面分别用这两个算法实现。
AC代码
class Solution {public: //简单模式匹配算法(BF算法) int strStr(string haystack, string needle) { int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = 0, j = 0; while (i < len && j < nl) { if (haystack[i] == needle[j]) { i++; j++; } else{ i = i - j + 1; j = 0; }//else }//while if (j == nl) return i - nl; else return -1; }};
KMP算法实现
class Solution {public: //简单模式匹配算法(BF算法) int strStr(string haystack, string needle) { int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = 0, j = 0; while (i < len && j < nl) { if (haystack[i] == needle[j]) { i++; j++; } else{ i = i - j + 1; j = 0; }//else }//while if (j == nl) return i - nl; else return -1; } //从字符串haystack的第pos个位置开始匹配 int KMP(const string &haystack, const string &needle, int pos) { int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = pos, j = 0; int *n = Next(needle); while (i < len && j < nl) { if (j == -1 || haystack[i] == needle[j]) { i++; j++; } else{ j = n[j]; }//else }//while if (j == nl) return i - nl; else return -1; } int* Next(const string &s) { int i = 0, j = -1; int next[500] ; int len = strlen(s.c_str()); next[0] = -1;; while (i < len) { while (j >-1 && s[i] != s[j]) j = next[j]; i++; j++; if (s[i] == s[j]) next[i] = next[j]; else next[i] = j; }//while return next; }};
GitHub测试程序源码
0 0
- LeetCode(28)Implement strStr()
- LeetCode (28)Implement strStr()
- LeetCode(28)Implement Strstr()
- [leetcode 28] Implement strStr()
- LeetCode[28]Implement strStr()
- leetcode-28 Implement strStr()
- [LeetCode 28]Implement strStr()
- leetcode 28 Implement strStr()
- Leetcode 28 Implement strStr()
- LeetCode 28 - Implement strStr()
- LeetCode 28:Implement strStr()
- leetcode 28 -- Implement strStr()
- leetcode[28]:Implement strStr()
- leetcode 28: Implement strStr()
- Leetcode #28 Implement strStr()
- leetCode #28 Implement strStr()
- Leetcode#28||Implement strStr()
- leetCode 28 Implement strStr()
- [Leetcode]Remove Nth Node From End of List
- IOS动画CABasicACnimationanimation
- 在动态web工程中jsp页面的EL表达式没有效果
- 一个经典例子让你彻彻底底理解java回调机制
- 内存管理实践
- LeetCode(28)Implement strStr()
- Android系统优化
- Boost::asio 学习笔记
- C - 语言
- Codeforces Round #Pi (Div. 2) B Berland National Library
- 线程中删除socket对象
- bottle(python的一个小的服务器框架)的源码阅读(一)
- 敌兵布阵(树状数组模板题)
- block