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

Commit 7446c16

Browse files
Add solution for Longest Substring Without Repeating Characters
1 parent 38aa0e8 commit 7446c16

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ Algorithm exercises from LeetCode implemented in Java v11.
8686
### Sliding Window
8787
- Minimum Size Subarray Sum | [Problem](https://leetcode.com/problems/minimum-size-subarray-sum) | [Solution](src/solutions/MinimumSizeSubarraySum.java)
8888
- Binary Subarrays With Sum | [Problem](https://leetcode.com/problems/binary-subarrays-with-sum) | [Solution](src/solutions/BinarySubarraysWithSum.java)
89+
- Longest Substring Without Repeating Characters | [Problem](https://leetcode.com/problems/longest-substring-without-repeating-characters) | [Solution](src/solutions/LongestSubstringWithoutRepeatingCharacters.java)
8990

9091
### Recursion
9192
- Closest Binary Search Tree Value | [Problem](https://leetcode.com/problems/closest-binary-search-tree-value)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package solutions;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
// [Problem] https://leetcode.com/problems/longest-substring-without-repeating-characters
7+
class LongestSubstringWithoutRepeatingCharacters {
8+
// Sliding window with HashMap
9+
// O(n) time, O(n) space
10+
public int lengthOfLongestSubstring(String s) {
11+
Map<Character, Integer> occurrences = new HashMap<>();
12+
int left = 0, maxLength = 0;
13+
for (int right = 0; right < s.length(); right++) {
14+
char c = s.charAt(right);
15+
Integer occurrence = occurrences.get(c);
16+
if (occurrence != null && occurrence >= left) {
17+
left = occurrence + 1;
18+
}
19+
occurrences.put(c, right);
20+
maxLength = Math.max(maxLength, right - left + 1);
21+
}
22+
return maxLength;
23+
}
24+
25+
// Test
26+
public static void main(String[] args) {
27+
LongestSubstringWithoutRepeatingCharacters solution = new LongestSubstringWithoutRepeatingCharacters();
28+
29+
String input1 = "abcabcbb";
30+
int expectedOutput1 = 3;
31+
int actualOutput1 = solution.lengthOfLongestSubstring(input1);
32+
System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1));
33+
34+
String input2 = "bbbbb";
35+
int expectedOutput2 = 1;
36+
int actualOutput2 = solution.lengthOfLongestSubstring(input2);
37+
System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2));
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /