Skip to content

Commit bcde39a

Browse files
add a solution for 3
1 parent 5e27b1a commit bcde39a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/com/fishercoder/solutions/_3.java

+25
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,29 @@ public int lengthOfLongestSubstring(String s) {
9595
return max;
9696
}
9797
}
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+
}
98123
}

src/test/java/com/fishercoder/_3Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ public class _3Test {
1111
private static _3.Solution2 solution2;
1212
private static _3.Solution3 solution3;
1313
private static _3.Solution4 solution4;
14+
private static _3.Solution5 solution5;
1415

1516
@BeforeClass
1617
public static void setup() {
1718
solution1 = new _3.Solution1();
1819
solution2 = new _3.Solution2();
1920
solution3 = new _3.Solution3();
2021
solution4 = new _3.Solution4();
22+
solution5 = new _3.Solution5();
2123
}
2224

2325
@Test
@@ -26,6 +28,7 @@ public void test1() {
2628
assertEquals(3, solution2.lengthOfLongestSubstring("abcabcbb"));
2729
assertEquals(3, solution3.lengthOfLongestSubstring("abcabcbb"));
2830
assertEquals(3, solution4.lengthOfLongestSubstring("abcabcbb"));
31+
assertEquals(3, solution5.lengthOfLongestSubstring("abcabcbb"));
2932
}
3033

3134
}

0 commit comments

Comments
 (0)