implement strstr()

思路

  • 利用String.substring(int beginIndex , int endIndex),endIndex所指的字符不包括(这貌似是比较通用的规律)
  • 排除边界(有一个String为 “” ,或者两个String均为 “”)情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution{
public int strStr(String haystack , String needle){
int l1 = haystack.length();
int l2 = needle.length();
if(l1 == 0 && l2 == 0)
return -1;
int count = 0;
String str = "";
for(; count < l1 - l2 + 1 ; count++){
str = haystack.substring(count , count + l2);
if(str.equals(needle))
break;
}
return str.equals(needle) ? count : -1;
}
}