LeetCode每日一练
Longest Substring Without Repeating Characters
/*
* @Author: fox
* @Date: 2022-04-20 09:26:20
* @LastEditors: fox
* @LastEditTime: 2022-04-20 09:45:00
* @Description: https://leetcode.com/problems/longest-substring-without-repeating-characters/
*/
function lengthOfLongestSubstring(s) {
const scanner = []
let longest = 0
for (const element of s) {
// 查找当前元素是否在数组中
const possibleIndex = scanner.indexOf(element)
// 如果当前元素已经在数组中,数组将删除从索引0到查找到的索引间的所有元素,包括当前元素
if (possibleIndex !== -1) { scanner.splice(0, possibleIndex + 1) }
// 将当前元素添加到数组中
scanner.push(element)
// longest = Math.max(longest, scanner.length)
// 比较最大值
longest = longest > scanner.length ? longest : scanner.length
}
return longest
}