leetcode-28-implement strstr()

题目

对于给定的字符串haystack和needle,如果needle是haystack的子串,返回needle在haystack中出现的首个下标,否则返回-1

描述

通过字符串截取,截取haystack中[i:i+needle.length()]的子串,与needle进行比较,遍历得到最终的结果

Java代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class  {
public int strStr(String haystack, String needle) {
if(needle.equals("")){
return 0;
}
int res = -1;
int len = needle.length();
String tmp;
for(int i = 0;i<=haystack.length()-len;i++){
tmp = haystack.substring(i,i+len);
if(tmp.equals(needle)){
res = i;
break;
}
}
return res;
}
}

Python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class (object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""

if not needle:
return 0
res = -1
ne_len = len(needle)
for i in range(len(haystack)-ne_len+1):
if haystack[i:i+ne_len] == needle:
return i
return res