Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
返回第一个匹配字符串的索引
问题:当needle为空时应返回什么?要看具体规则讨论。
解法:
1.
public int strStr(String haystack, String needle) {
int lens = haystack.length();
int lenn = needle.length();
if(lens < lenn) return -1;
else if(lenn == 0) return 0;
else{
for(int loop=0 ; loop<=lens-lenn ; loop++){
if(needle.compareTo(haystack.substring(loop,loop+lenn))==0){
//判断语句也可写成haystack.substring(i,i+l2).equals(needle)
return loop;
}
}
return -1;
}
}
2.
public int strStr(String haystack, String needle) {
if(needle.length()==0) return 0;
for(int i=0; i<haystack.length(); i++){
if(i+needle.length()>haystack.length()) return -1;
for(int j=0; j<needle.length(); j++){
if(haystack.charAt(i+j)!=needle.charAt(j)) break;
if(j==needle.length()-1) return i;
}
}
return -1;
}