一開始 理解錯了 需求 寫的有點花了~~~
而且 其實 這個題目裏面 涉及了一丟丟 小回溯的問題~~!!!
另外 用 indexof 一上來就找到 那個位置 ,某個角度會更好喲!!!
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當 needle
是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle
是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
let start = "";
if(needle.length==0){
// if(haystack.length==0){
// return 0;
// }else{
// return -1;
// }
return 0;
}else if(needle.length==1){
if(haystack.length==0){
return -1;
}else{
if(haystack.includes(needle)){
return haystack.indexOf(needle);
}else{
return -1;
}
}
}else if(needle==haystack){
return 0;
}else if(needle.length>haystack.length){
return -1;
}else{
start = needle.substr(0,1);
}
let rsFlg = true;
let index = -1;
for(let i = 0 ;i< haystack.length;i++){
// let tempStr = haystack.substr(i,1);
if(haystack.substr(i,1)==start){
index = i;
// i++;
// for(let j=1;j<needle.length;i++,j++){
// console.log(i);
// console.log(haystack.substr(i,1));
// console.log(j);
// console.log(needle.substr(j,1));
// if(haystack.substr(i,1)!=needle.substr(j,1)){
// rsFlg = false;
// break;
// }
// }
// console.log(rsFlg);
if(haystack.substr(i,needle.length)!=needle){
rsFlg = false;
if(haystack.substring(index+1).includes(start)){
rsFlg = true;
// index = -1;
continue;
}else{
break;
}
}else{
break;
}
// if(rsFlg){
// break;
// }
}
// if(!rsFlg){
// // i--;
// // i--;
// if(haystack.substring(index).includes(start)){
// rsFlg = true;
// // index = -1;
// continue;
// }else{
// break;
// }
// // continue;
// }
}
if(!rsFlg||(index==-1)){
return -1;
}
return index;
};