我不太明白,同樣的例子'''',在Leetcode中是-1,然鵝在eclipse中是0
然後我明白了,是""的原因,如果字串爲空,則返回0的位置 實質上上KMP算法
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
class Solution {
public static int strStr(String haystack, String needle) {
char ch;
// int index = 0;
int N = needle.length();
if(N == 0 )
return 0;
for(int i = 0; i < haystack.length() - N + 1;i++){
if(haystack.substring(i,i+N).equals(needle)) {
return i;
}
// ch = haystack.charAt(i);
// if( index < needle.length() && ch == needle.charAt(index)){
// index++;
// if(index == needle.length()){
// return i -index +1;
// }
// }else {
// index = 0;
// }
// }
}
return -1;
}
}