Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
1 |
Input: haystack = "hello", needle = "ll" |
Example 2:
1 |
Input: haystack = "aaaaa", needle = "bba" |
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C’s strstr() and Java’s indexOf()).
思路
- 如果是pattern是空,返空。
- 如果pattern比text还要长,返-1。
- 从text的0开始遍历,一直到text剩下的字符串等于pattern的时候为止。不用遍历到text的末尾,这样可以提高效率。
My code in cpp
1 |
int (string haystack, string needle) { |
KMP算法
coming soon~~
总结
- 字符串匹配问题
- 暴力搜索法 O(m*n)
- KMP算法O(m+n)
近期评论