实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
输入: haystack = "hello", needle = "ll"
输出: 2
输入: haystack = "aaaaa", needle = "bba"
输出: -1
滑动窗口
- 以needle的字符串长度在haystack字符串上滑动
- 不断与needle进行匹配,如果相等,则返回窗口的开始索引
let strStr = (haystack, needle) => {
let l = haystack.length;
let r = needle.length;
for (let i = 0; i < l - r + 1; i++) {
if (haystack.substring(i , i + r) === needle)
return i;
}
return -1;
}
console.log(strStr("hello", "ll"));
console.log(strStr("aaaaa", "bba"));
func strStr(haystack, needle string) int {
l := len(haystack)
r := len(needle)
for i := 0; i < l - r + 1; i++ {
if haystack[i:i + r] == needle {
return i
}
}
return -1
}class Solution {
public int strStr(String haystack, String needle) {
int l = haystack.length(), r = needle.length();
for (int i = 0; i < l - r + 1; i++) {
if (haystack.substring(i, i + r).equals(needle))
return i;
}
return -1;
}
}