(算法分析Week6)Implement strStr()[Easy]
2017-10-14 13:31
232 查看
28. Implement strStr()
Description
Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
也就是字符串模式匹配,返回第一个对应匹配的下标。
Solution
KMP算法,具体可以看这篇博客Complexity analysis
O(n+m)Code
class Solution { public: void Next(int* &next, string pattern) { next[0] = -1; int k = -1; int j = 0; int n = pattern.length(); while (j < n - 1) { if (k == -1 || pattern[j] == pattern[k]) { j++; k++; next[j] = k; cout << next[j]; } else { k = next[k]; } } } int strStr(string haystack, string needle) { int length = needle.length(); int *arr = new int[length]; /*一个基础知识的吐槽,是[]不是(),否则delete对应会出错*/ Next(arr, needle); int i, j; i = j = 0; while (i < haystack.length() && j < (int)needle.length()) { /*这里要注意,string.length()是一个无符号数!当j=-1与其比较,会返回大于的结果,直接跳出循环 一直不过就是因为这里,IDE跑的时候warning才发现 */ if (j == -1 || haystack[i] == needle[j]) { i++; j++; } else { j = arr[j]; } } delete []arr; if (j >= needle.length()) { return i - needle.length(); } return -1; } };
Result
相关文章推荐
- 算法分析与设计——LeetCode刷题之TwoSum(easy)
- Easy Audio CD Burner 算法分析及逆向推算(图)
- (算法分析Week14)House Robber[Easy]
- (算法分析Week7)Remove Element[Easy]
- LeetCode_28---Implement strStr() [KMP算法,字符匹配算法]
- 算法系列——Implement strStr()
- (算法分析Week9)Remove Duplicates from Sorted Array[Easy]
- (算法分析Week4)Count and Say[Easy]
- LeetCode OJ 28 Implement strStr() [Easy]
- (算法分析Week3)Reverse Integer[Easy]
- (算法分析Week5)Palindrome Number[Easy]
- (算法分析Week8)Climbing Stairs[Easy]
- (算法分析Week18)1-bit and 2-bit Characters[Easy]
- (算法分析Week6)Longest Palindromic Substring[Medium]
- (算法分析Week3)Merge Two Sorted Lists[Easy]
- 【Leetcode】【Easy】Implement strStr()
- LeetCode-Easy-Java-Implement strStr()
- 【leetcode】Implement strStr() (easy)
- (算法分析Week1)Majority Element[Easy]
- leetcode 题解 || Implement strStr() 问题 (即 KMP 算法实现)