algorighm/leetcode/中等/无重复字符的最长子串.js

89 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* 3. 无重复字符的最长子串
已解答
中等
相关标签
相关企业
给定一个字符串 s ,请你找出其中不含有重复字符的 最长
子串
的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
*/
// /*
// 思路:遍历每一个字符开始的最长字串有多少个,取最长的
// /**
// * @param {string} s
// * @return {number}
// */
// function lengthOfLongestSubstring(s) {
// let maxLength = 0;
// for (let i = 0; i < s.length; i++) {
// const set = new Set();
// let length = 0;
// for (let j = i; j < s.length; j++) {
// if (!set.has(s[j])) {
// set.add(s[j]);
// length++;
// maxLength = Math.max(maxLength, length);
// } else {
// break;
// }
// }
// }
// return maxLength;
// }
/*
思路用一个set数组来保存当前遍历的最长不重复的字符定义left表示不重复字符串开始的字符
right表示不重复字符串结束的字符right一直往后面遍历如果在set集合中没有重复的字符就直接
把这个字符加入到set集合中去如果在set集合中有这个字符就使用使用left下标代表的字符开始删除
知道没有right所指向的那个字符此时set集合中的所有字符表示的就是一个新的不重复字符我们那它
和之前的不重复字符比较,直到遍历结束找到最长的不重复字符
*/
/**
* @param {string} s
* @return {number}
*/
function lengthOfLongestSubstring(s) {
const charSet = new Set();
let maxLength = 0;
let left = 0;
const len = s.length;
for (let right = 0; right < len; right++) {
while (charSet.has(s.charAt(right))) {
charSet.delete(s.charAt(left));
left++;
}
charSet.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
console.log(lengthOfLongestSubstring('aaaaabcdefgca'));