javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
let result = '',
max = 0
for (let i = 0; i < s.length; i++) {
if (result.indexOf(s[i]) === -1) {
result += s[i]
max = Math.max(result.length, max)
} else {
result = result.slice(result.indexOf(s[i]) + 1) + s[i]
}
}
return max
}优化的 Map
javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
let map = new Map(),
max = 0
for (let i = 0, j = 0; j < s.length; j++) {
if (map.has(s[j])) {
i = Math.max(map.get(s[j]) + 1, i)
}
max = Math.max(max, j - i + 1)
map.set(s[j], j)
}
return max
}