您的位置:首页 > 其它

28. Implement strStr()

2016-01-06 08:50 603 查看
题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
brute-force 复杂度为O(MN)。下次有机会写一个O(n)的KMP

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle)==0:return 0
for i,c in enumerate(haystack):
tmp = haystack[i:i+len(needle)]
if tmp==needle:return i
return -1


class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(m==0)return 0;
for(int i=0;i<=n-m;i++)
{
string tmp = haystack.substr(i,m);
if(tmp==needle)return i;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: