3.无重复字符的最长子串

时游小于 1 分钟LeetCode

3.无重复字符的最长子串

/*
 * @lc app=leetcode.cn id=3 lang=typescript
 *
 * [3] 无重复字符的最长子串
 */

// @lc code=start
function lengthOfLongestSubstring(s: string): number {
	// 采用滑动窗口方法
	// 1. 记录最优解、最大长度
	let maxArr: string[] = [];
	let maxLen: number = 0;
	// 2. 定义l、r记录左右
	let l = 0,
		r = 0;
	let maxLen = 0;
	// 3. 固定l,r开始右移动
	while (r < s.length) {
		let index = maxArr.indexOf(s[r]);
		if (index === -1) {
			// l不动
			maxArr.push(s[r]);
			maxLen = Math.max(maxArr.length, maxLen);
			r++;
		} else {
			maxArr.shift();
			l += index + 1;
		}
	}
	console.log(maxArr);

	return maxLen;
}

lengthOfLongestSubstring("jbpnbwwd");
// @lc code=end

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