Question
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
- 0 <= s.length <= 5 * 104
- s consists of English letters, digits, symbols and spaces.
Let's Go!
Solve by using PREP.
- P - One parameter of type string
- R - A return of type number that represents the length of the longest substring that does not repeat characters
- E - Examples provided by question. (See Above)
- P - See Below
var lengthOfLongestSubstring = function(s) {
// Assign i to 0 to track index of s
// Assign count to [ 0 ] to track lengths of all substrings
// Assign start to 0 to track the beginning idx of a new substring
// Iterate over s while i < s.length
// If slice of s from start to i does not include the current char at i of s
// Add 1 to the last element of the count array
// Add 1 to i
// Else
// Add a new length of 0 to last element of count array
// Assign start and i to the previous index where the char at i of s appeared and then add 1
// return the largest number within the count array
}
Translate into code...
var lengthOfLongestSubstring = function(s) {
let start = 0
let i = 0
let count = [ 0 ]
while (i < s.length) {
if (!s.slice(start, i).includes(s.charAt(i))) {
count[count.length - 1]++
i++
} else {
count[count.length] = 0
start, i = s.slice(0, i).lastIndexOf(s.charAt(i)) + 1
}
}
return count.reduce((max, current) => current > max ? current : max)
}
Conclusion
& Remember... Happy coding, friends! =)
Discussion (0)