Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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) {
let temp = "";
let maxLen = 0; //记录最长的子串长度
for (let chart of s) {
let index = temp.indexOf(chart);
if (index >= 0) { //如果该字符已经出现过 删掉之前的部分。
temp = temp.substring(index + 1);
}
temp += chart;
if (temp.length > maxLen) {
maxLen = temp.length;
}
}
return maxLen;
};