問題描述
實現(xiàn) strStr() 函數(shù)。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個位置 (從0開始)。如果不存在实撒,則返回 -1。
示例
輸入: haystack = "hello", needle = "ll"
輸出: 2
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
思路
第一秒KMP,第二秒不會寫……h(huán)hhhh源哩。與上題一樣,利用雙指針進行循環(huán)匹配鸦做,效率上肯定不如KMP算法高效励烦。外循環(huán)的索引表示將要匹配的子串在原字符串中的起始位置,內(nèi)循環(huán)的索引表示匹配子串的位置泼诱。不使用內(nèi)外索引均表示字符串起始位置坛掠,這樣做是為了避免子串比原串長導(dǎo)致誤判的情況。如:haystack = "aaaa", neddle = "aaaaaaa"治筒。簡單題老老實實雙指針屉栓,KMP學(xué)了沒啥用
//報錯的代碼
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")){
return 0;
}
for(int i=0; i<haystack.length(); i++){
int j=0;
for(; j<needle.length(); j++){
if(haystack.charAt(i) != needle.charAt(j)){
break;
}else {
continue;
}
}
if(j == needle.length()){
return i;
}
}
return -1;
}
}
//成功執(zhí)行的代碼
class Solution {
public int strStr(String haystack, String needle) {
int hLength = haystack.length(), nLength = needle.length();
for(int i = 0; i < hLength-nLength+1; i ++){
int j=0;
for(; j < nLength; j++){
if(haystack.charAt(i+j) != needle.charAt(j)){
break;
}
}
if(j == nLength){
return i;
}
}
return -1;
}
}