28.找出字符串中第一个匹配项的下标

时游小于 1 分钟LeetCode

28.找出字符串中第一个匹配项的下标

/*
 * @lc app=leetcode.cn id=28 lang=typescript
 *
 * [28] 找出字符串中第一个匹配项的下标
 */

// @lc code=start
function strStr(haystack: string, needle: string): number {
	let l = 0;
	// 限定l范围
	while (l < haystack.length - needle.length + 1) {
		// 第一项符合
		if (haystack[l] == needle[0]) {
			let s = haystack.slice(l, l + needle.length);
			if (s === needle) return l;
		}
		l++;
	}
	return -1;
}

console.log(strStr("hello", "ll"));
// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...