-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-substring.js
More file actions
45 lines (44 loc) · 1.22 KB
/
longest-substring.js
File metadata and controls
45 lines (44 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
*
* Given a string, find the length of the longest substring without repeating characters.
*
* Input: "abcabcbb"
* Output: 3
* Explanation: The answer is "abc", with the length of 3.
*
* Input: "bbbbb"
* Output: 1
* Explanation: The answer is "b", with the length of 1.
*
* 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.
*
* */
var findLargestSubstring = input => {
var chars = input.split("");
var curr_char;
var str = "";
var longest_string = "";
var hash = {};
for (var i = 0; i < chars.length; i++) {
curr_char = chars[i];
if (!hash[chars[i]]) {
str += curr_char;
hash[chars[i]] = { index: i };
} else {
if (longest_string.length <= str.length) {
longest_string = str;
}
var prev_dupeIndex = hash[curr_char].index;
var str_FromPrevDupe = input.substring(prev_dupeIndex + 1, i);
str = str_FromPrevDupe + curr_char;
hash = {};
for (var j = prev_dupeIndex + 1; j <= i; j++) {
hash[input.charAt(j)] = { index: j };
}
}
}
return longest_string.length > str.length ? longest_string : str;
};