实现-str-str
题目
给你两个字符串 haystack
和 needle
, 请你在 haystack
字符串中找出 needle
字符串出现的第一个位置(下标从 0
开始). 如果不存在, 则返回 -1
.
提示:
1 <= haystack.length, needle.length <= 10⁴
haystack
和needle
仅由小写英文字符组成
示例
输入: haystack = "hello"
, needle = "ll"
输出: 2
题解
- JavaScript
- Rust
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
const m = haystack.length
const n = needle.length
for (let i = 0; i + n <= m; i++) {
if (haystack.slice(i, i + n) === needle) return i
}
return -1
};
pub fn str_str(haystack: String, needle: String) -> i32 {
let (mut i, mut j) = (0, needle.len(););
while j <= haystack.len() {
if haystack[i..j] == needle {
return i as i32;
}
i += 1;
j += 1;
}
-1
}