问题描述:
Java代码:
class Solution {
public int strStr(String haystack, String needle) {
int n1 = haystack.length();
int n2 = needle.length();
if (n2 == 0) {
return 0;
}
if (n1 < n2) {
return -1;
}
for (int i = 0; i <= n1 - n2; i++) {
if (haystack.substring(i, i + n2).equals(needle)) {
return i;
}
}
return -1;
}
}
python代码1:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
python代码2:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
n1, n2 = len(haystack), len(needle)
if n2 == 0:
return 0
for i in range(n1 - n2 + 1):
if haystack[i:i+n2] == needle:
return i
return -1