Longest Substring Without Repeating Characters
Problem
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb"
, the answer is "abc"
, which the length is 3.
Given
"bbbbb"
, the answer is "b"
, with the length of 1.
Given
"pwwkew"
, 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.Difficulty | Related Topics | Similar Questions | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
Medium
|
|
|
Solution
Here is the solution for the problem in javascript without Regular Expression (Regex)
const longestString = str => {
obj = {};
longest = [];
current = [];
for (let i=0; i<str.length; i++) {
if (obj[str[i]] === undefined) {
obj[str[i]] = 1;
current.push(str[i]);
} else {
if (current.length > longest.length) {
longest = [...current];
current = [];
obj = {};
obj[str[i]] = 1;
current.push(str[i]);
}
}
}
return longest.join('');
}
console.log(longestString('ababcababcababcababcababcababc'));
Output
abc
Run this code here: https://repl.it/@VinitKhandelwal/longest-string-javascript
Comments
Post a Comment