Skip to content

Commit

Permalink
add: 在字符串中查找给定的子字符串出现的第一个位置
Browse files Browse the repository at this point in the history
  • Loading branch information
xldeng committed Nov 4, 2022
1 parent b62f7a6 commit e337119
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
5. [电话号码中的字符组合](https://github.com/dengshasha/algorithm-study/blob/master/string/letterCombOfPhoneNum.js) || [leetcode地址](https://leetcode.com/problems/letter-combinations-of-a-phone-number/submissions/)
6. [爬楼梯](https://github.com/dengshasha/algorithm-study/blob/master/string/climbStairs.js) || [leetcode地址](https://leetcode.com/problems/climbing-stairs/)
7. [在字符串中查找满足条件的最短子串](https://github.com/dengshasha/algorithm-study/blob/master/string/minWindowSubstr.js) || [leetcode地址](https://leetcode.com/problems/minimum-window-substring/)

8. [在字符串中查找给定的子字符串出现的第一个位置](https://github.com/dengshasha/algorithm-study/blob/master/string/findFirstPosOfStr.js) || [leetcode地址](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/)

### 数组
1. [数组各项,除该项外累乘的结果](https://github.com/dengshasha/algorithm-study/blob/master/array/productArrayExceptSelf.js) || [leetcode地址](https://leetcode.com/problems/product-of-array-except-self/submissions/)
Expand Down
38 changes: 38 additions & 0 deletions string/findFirstPosOfStr.js
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
}

0 comments on commit e337119

Please sign in to comment.