Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbcde39a

Browse files
add a solution for 3
1 parent5e27b1a commitbcde39a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,29 @@ public int lengthOfLongestSubstring(String s) {
9595
returnmax;
9696
}
9797
}
98+
99+
publicstaticclassSolution5 {
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+
publicintlengthOfLongestSubstring(Strings) {
107+
intstartIndex =0;
108+
intlongest =0;
109+
Map<Character,Integer>map =newHashMap<>();
110+
for (inti =0;i <s.length();i++) {
111+
if (map.containsKey(s.charAt(i))) {
112+
IntegerremovedIndex =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+
returnlongest;
121+
}
122+
}
98123
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ public class _3Test {
1111
privatestatic_3.Solution2solution2;
1212
privatestatic_3.Solution3solution3;
1313
privatestatic_3.Solution4solution4;
14+
privatestatic_3.Solution5solution5;
1415

1516
@BeforeClass
1617
publicstaticvoidsetup() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp