Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if (s.length < 1) {
return 0;
}
let current = 1;
let result = 1;
let tmp = s[0];
for (let i = 1; i < s.length; i++) {
let idx = tmp.indexOf(s[i]);
tmp += s[i];
if (idx < 0) {
current++;
} else {
tmp = tmp.substring(idx + 1, tmp.length);
current = tmp.length;
}
if (current >= result) {
result = current;
}
}
return result;
};
解题思路:子串一定是连续的字符串,因此当找到一个字符在“目前的子串”时,则重置该“目前的子串”,剔除重复字符之前的所有字符,然后继续查找,找到最终的结果。