LeetCode 第 3 號問題:無重複字符的最長子串
題目地址
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
題目描述
給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因爲無重複字符的最長子串是 "abc",所以其長度爲 3。
思路
1.首先取 res 爲輸入字符串的第一個字符
2.判斷第二個字符是否存在 s 中,並判斷其位置,如果存在就刪除所在位置的之前的所有元素,包括存在的元素,否則 res 加上地二個字符
3.重複步驟二
4.既能返回長度 newLen,也能返回最後位置的最長的字符串 newRes
代碼
/**
* @param {string} s
* @return {number}
*/
const lengthOfLongestSubstring = function (str) {
let len = str.length;
if (len < 1) return 0;
let res = str[0];
let newLen = 1;
let newRes = str[0];
for (let i = 1; i < len; i++) {
let j = res.indexOf(str[i]);
if (j === -1) {
res = res + str[i];
}
if (j !== -1) {
res = res.substring(j + 1, res.length);
res = res + str[i];
}
if (res.length >= newLen) {
newLen = res.length;
newRes = res;
}
}
return newLen;
};