Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Java
public class Solution {
public int strStr(String haystack, String needle) {
int l1 = haystack.length(), l2=needle.length();
if(l1<l2) return -1;
boolean match = true;
for(int i=0; i<=l1-l2; i++){
match = true;
for(int j=0; j<l2; j++){
if(haystack.charAt(i+j)!=needle.charAt(j)) {match=false;break;}
}
if(match) return i;
}
return -1;
}
}
Python
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# try:
# return haystack.index(needle)
# except:
# return -1
for i in range(len(haystack)-len(needle)+1):
found=True
for j in range(len(needle)):
if haystack[i+j]!=needle[j]:
found=False
break
if found:
return i
return -1