File tree 2 files changed +28
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -95,4 +95,29 @@ public int lengthOfLongestSubstring(String s) {
95
95
return max ;
96
96
}
97
97
}
98
+
99
+ public static class Solution5 {
100
+ /**
101
+ * Sliding Window, my completely original idea on 9/17/2021.
102
+ * Basically, keep moving the left boundary towards the right and keep updating the result along the way.
103
+ * O(n) time
104
+ * O(n) space
105
+ */
106
+ public int lengthOfLongestSubstring (String s ) {
107
+ int startIndex = 0 ;
108
+ int longest = 0 ;
109
+ Map <Character , Integer > map = new HashMap <>();
110
+ for (int i = 0 ; i < s .length (); i ++) {
111
+ if (map .containsKey (s .charAt (i ))) {
112
+ Integer removedIndex = map .get (s .charAt (i ));
113
+ if (removedIndex >= startIndex ) {
114
+ startIndex = removedIndex + 1 ;
115
+ }
116
+ }
117
+ map .put (s .charAt (i ), i );
118
+ longest = Math .max (longest , i - startIndex + 1 );
119
+ }
120
+ return longest ;
121
+ }
122
+ }
98
123
}
Original file line number Diff line number Diff line change @@ -11,13 +11,15 @@ public class _3Test {
11
11
private static _3 .Solution2 solution2 ;
12
12
private static _3 .Solution3 solution3 ;
13
13
private static _3 .Solution4 solution4 ;
14
+ private static _3 .Solution5 solution5 ;
14
15
15
16
@ BeforeClass
16
17
public static void setup () {
17
18
solution1 = new _3 .Solution1 ();
18
19
solution2 = new _3 .Solution2 ();
19
20
solution3 = new _3 .Solution3 ();
20
21
solution4 = new _3 .Solution4 ();
22
+ solution5 = new _3 .Solution5 ();
21
23
}
22
24
23
25
@ Test
@@ -26,6 +28,7 @@ public void test1() {
26
28
assertEquals (3 , solution2 .lengthOfLongestSubstring ("abcabcbb" ));
27
29
assertEquals (3 , solution3 .lengthOfLongestSubstring ("abcabcbb" ));
28
30
assertEquals (3 , solution4 .lengthOfLongestSubstring ("abcabcbb" ));
31
+ assertEquals (3 , solution5 .lengthOfLongestSubstring ("abcabcbb" ));
29
32
}
30
33
31
34
}
You can’t perform that action at this time.
0 commit comments