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.
Example 4:
Input: s = ""
Output: 0
Constraints:
- 0 <= s.length <= 5 * 104
- s consists of English letters, digits, symbols and spaces.
Let's Go!
Solve by using PREP.
- P - A string s of letters, digits, symbols and spaces
- R - Return a number which is the length of the Longest Substring Without Repeating Characters
- E - Examples provided by question. (See Above)
- P - See Below
Attempt 1
var lengthOfLongestSubstring = function(s) {
const arr = s.split('')
let charMap = {}
let count = [ 0 ]
for (let i=0; i<arr.length; i++) {
if (!charMap[arr[i]]) {
count[count.length - 1] = count[count.length - 1]+1
charMap[arr[i]] = 1
} else {
charMap = {}
charMap[arr[i]] = 1
count[count.length] = 1
}
}
return count.reduce((max, current) => current > max ? current : max)
};
Results of Attempt 1
console.log(lengthOfLongestSubstring("abcabcbb")) // 3 - PASS
console.log(lengthOfLongestSubstring("aab")) // 2 - PASS
console.log(lengthOfLongestSubstring("dvdf")) // 2 - FAIL (CORRECT is 3)
To Be Continued...
Top comments (0)