Skip to content

Commit 946fb68

Browse files
committed
longest substring without repeating chars
1 parent 3d4f93f commit 946fb68

File tree

1 file changed

+73
-12
lines changed

1 file changed

+73
-12
lines changed

3 Longest Substring Without Repeating Characters.js

Lines changed: 73 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,95 @@
33
* @return {number}
44
*/
55

6-
7-
var lengthOfLongestSubstring = function(s) {
8-
if(s === null || s.length === 0){
6+
var lengthOfLongestSubstring = function (s) {
7+
if (s === null || s.length === 0) {
98
return 0;
109
}
11-
10+
1211
var map = {};
1312
var len = 0;
1413
var maxLen = len;
1514
var start = 0;
1615

1716
// scan from left to right.
18-
for(var i = start; i < s.length; i++){
17+
for (var i = start; i < s.length; i++) {
1918
c = s[i];
2019

21-
if(map[c] !== undefined && map[c] >= start) {
20+
if (map[c] !== undefined && map[c] >= start) {
2221
start = map[c] + 1; // start new search with repeated word's last location + 1
2322
len = i - start; // real length -> from for example 3 to 5 is 3, so it's 5-3+1 and + 1 happens later
2423
}
25-
24+
2625
len++; // real length -> from for example 3 to 5 is 3, so it's 5-3+1 and + 1 happens later
27-
28-
if(len > maxLen){
26+
27+
if (len > maxLen) {
2928
maxLen = len;
3029
}
31-
30+
3231
map[c] = i;
3332
}
34-
33+
3534
return maxLen;
36-
};
35+
};
36+
37+
38+
/**
39+
* Input: "abcabcbb"
40+
* Output: 3
41+
* Explanation: The answer is "abc", with the length of 3.
42+
*
43+
* Input: "bbbbb"
44+
* Output: 1
45+
* Explanation: The answer is "b", with the length of 1.
46+
*
47+
* Input: "pwwkew"
48+
* Output: 3
49+
* Explanation: The answer is "wke", with the length of 3.
50+
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
51+
*/
52+
53+
const longestSubstring = (s) => {
54+
/**
55+
* start : 0
56+
* end: 0
57+
* map: {a, b ,c}
58+
*
59+
* abcabcbb
60+
*
61+
* size: 3
62+
*/
63+
// empty string return 0
64+
if (!s) return 0;
65+
66+
let start = 0,
67+
end = 0;
68+
const map = [];
69+
let result = 0;
70+
71+
while (end < s.length) {
72+
// loop through s and find the biggest size
73+
// if(map.indexOf(s[end]) > -1) {
74+
// map.shift();
75+
// start++;
76+
// }
77+
78+
while (map.indexOf(s[end]) > -1) {
79+
map.shift();
80+
start++;
81+
}
82+
83+
map.push(s[end]);
84+
85+
end++;
86+
// console.log(start, end, map);
87+
88+
result = Math.max(result, end - start);
89+
}
90+
return result;
91+
92+
}
93+
94+
95+
console.log(longestSubstring('bbbb')); // 1
96+
console.log(longestSubstring('abcabcbb')); // 3
97+
console.log(longestSubstring('pwwkett')); // 4

0 commit comments

Comments
 (0)