Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
Java:
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxl=0,left=0;
Map<Character,Integer> dic=new HashMap<>();
for (int i=0;i<s.length();i++){
char c=s.charAt(i);
if (dic.containsKey(c) && dic.get(c)>=left)
left=dic.get(c)+1;
dic.put(c,i);
maxl=Math.max(maxl,i-left+1);
}
return maxl;
}
}
Python:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left,maxl=0,0
dic={}
for i,c in enumerate(s):
if c in dic and dic[c]>=left:
left=dic[c]+1
maxl=max(maxl, i-left+1)
dic[c]=i
return maxl
JS:
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let currentSubstring = '';
let longestSubstring = '';
[...s].forEach(char => {
if (!currentSubstring.includes(char)) {
currentSubstring += char;
if (currentSubstring.length > longestSubstring.length) longestSubstring = currentSubstring;
} else {
// found a duplicate char, truncate our currentString after the duplicate and concatenate the char
currentSubstring = currentSubstring.substring(currentSubstring.indexOf(char) + 1) + char;
}
});
return longestSubstring.length;
};
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
visited = {}
output = "";
start = 0
for end in range(len(s)):
currChar = s[end]
if currChar in visited:
start = max(visited[currChar]+1, start);
if len(output) < end - start + 1:
output = s[start:end+1]
visited[currChar] = end
return len(output)