Implement strStr()
Problem: Implement strStr()
Just scan the string to solve the problem.
Code in Python:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
m, n = len(haystack), len(needle)
for i in xrange(m-n+1):
if haystack[i:i+n] == needle: return i
return -1
Code in Java:
public class Solution {
public int strStr(String haystack, String needle) {
int m = haystack.length(), n = needle.length();
for (int i = 0; i <= m-n; i++) {
if (haystack.substring(i, i+n).equals(needle))
return i;
}
return -1;
}
}