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.
判读一个字符串是否是另一个字符串的子串~可以用brute force的方法来解
Leetcode提供的Solution:
O(nm) runtime, O(1) space – Brute force:
You could demonstrate to your interviewer that this problem can be solved using known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, and the Boyer- Moore algorithm. Since these algorithms are usually studied in an advanced algorithms class, it is sufficient to solve it using the most direct method in an interview – The brute force method.
The brute force method is straightforward to implement. We scan the needle with the haystack from its first position and start matching all subsequent letters one by one. If one of the letters does not match, we start over again with the next position in the haystack.
The key is to implement the solution cleanly without dealing with each edge case separately.
class Solution:
# @param haystack, a string
# @param needle, a string
# @return an integer
def strStr(self, haystack, needle):
for i in xrange(len(haystack) - len(needle) + 1):
existFlag = True
for j in xrange(len(needle)):
if haystack[i + j] != needle[j]:
existFlag = False
break
if existFlag == True:
return i
return -1

本文介绍了一种简单直接的方法来解决字符串匹配问题:通过遍历目标字符串并逐一比较子串来寻找匹配项的位置。该方法虽然效率较低,但在面试场景中易于理解和实现。
332

被折叠的 条评论
为什么被折叠?



