-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
xldeng
committed
Nov 4, 2022
1 parent
b62f7a6
commit e337119
Showing
2 changed files
with
39 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* Created by dengxuelian on 2022/11/4 | ||
*/ | ||
/** | ||
* @param {string} haystack | ||
* @param {string} needle | ||
* @return {number} | ||
*/ | ||
// 解法1 | ||
var strStr = function(haystack, needle) { | ||
let h_size = haystack.length, n_size = needle.length; | ||
|
||
for(let i = 0; i <= h_size - n_size; i++) { | ||
if(haystack[i] !== needle[0]) continue; | ||
if(findSubStr(i, needle)) { | ||
return i | ||
} | ||
} | ||
|
||
function findSubStr(index, str) { | ||
if(str === '') return true; | ||
if(index >= h_size || haystack[index] !== str[0]) return false; | ||
return findSubStr(index+1, str.slice(1)) | ||
} | ||
return -1 | ||
}; | ||
|
||
//解法2 | ||
var strStr_1 = function(haystack, needle) { | ||
let h_size = haystack.length, n_size = needle.length; | ||
let start = 0, end = n_size; | ||
while(end <= h_size) { | ||
if(haystack.slice(start, end) === needle) return start; | ||
start++; | ||
end++; | ||
} | ||
return -1 | ||
} |