leetcode28.Implement strStr()

题目要求

1
在子字符串中寻找目标字符串,并返回该字符串第一次出现时的下标

思路一

在原字符串中中寻找目标字符串首字母的下标,并提取子字符串,若该字符串的开头等于目标字符串,则返回该下标
优点:速度相对较快
缺点:深度依赖api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int strStr(String haystack, String needle) {
int haystackLength = haystack.length();
int needleLength = needle.length();
if(haystackLength<needleLength){
return -1;
}else if(needleLength==0){
return 0;
}
char start = needle.charAt(0);
int index = haystack.indexOf(start);
while(index!=-1){
if(index+needleLength>haystackLength){
index = -1;
break;
}
if(haystack.substring(index).startsWith(needle)){
break;
}
int tempIndex = haystack.substring(index+1).indexOf(start);
index = tempIndex==-1?-1:(tempIndex+index+1);
}
return index;
}

思路二

提取当前下标的子字符串并判断开头是否相等,相等则返回该下标

1
2
3
4
5
6
7
8
9
10
11
12
13
public int strStr2(String haystack, String needle){
int index = 0;
for( ; index+needle.length()<=haystack.length() ; index++){
if(haystack.substring(index).startsWith(needle)){
//if(haystack.substring(index, index+needle.length).equals(needle){
return index;
}
}
if(index+needle.length()==haystack.length()){
index = -1;
}
return index;
}