Skip to content

Commit e4e5920

Browse files
solves #3090: Maximum Length Substring With Two Occurrences in java
1 parent c14dd2d commit e4e5920

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -899,7 +899,7 @@
899899
| 3074 | [Apple Redistribution into Boxes](https://leetcode.com/problems/apple-redistribution-into-boxes) | [![Java](assets/java.png)](src/AppleRedistributionIntoBoxes.java) | |
900900
| 3079 | [Find the Sum of Encrypted Integers](https://leetcode.com/problems/find-the-sum-of-encrypted-integers) | [![Java](assets/java.png)](src/FindTheSumOfEncryptedIntegers.java) | |
901901
| 3083 | [Existence of a Substring in a String and Its Reverse](https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse) | [![Java](assets/java.png)](src/ExistenceOfASubstringInAStringAndItsReverse.java) | |
902-
| 3090 | [Maximum Length Substring With Two Occurrences](https://leetcode.com/problems/maximum-length-substring-with-two-occurrences) | | |
902+
| 3090 | [Maximum Length Substring With Two Occurrences](https://leetcode.com/problems/maximum-length-substring-with-two-occurrences) | [![Java](assets/java.png)](src/MaximumLengthSubstringWithTwoOccurrences.java) | |
903903
| 3095 | [Shortest Subarray With OR at Least K I](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i) | | |
904904
| 3099 | [Harshad Number](https://leetcode.com/problems/harshad-number) | | |
905905
| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | | |

Diff for: src/MaximumLengthSubstringWithTwoOccurrences.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/maximum-length-substring-with-two-occurrences
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class MaximumLengthSubstringWithTwoOccurrences {
9+
public int maximumLengthSubstring(String s) {
10+
final Map<Character, Integer> frequencies = new HashMap<>();
11+
int maxLength = 1;
12+
13+
for (int left = 0, right = 0 ; left < s.length() && right < s.length() ; ) {
14+
if (frequencies.getOrDefault(s.charAt(right), 0) == 2) {
15+
frequencies.put(s.charAt(left), frequencies.get(s.charAt(left)) - 1);
16+
left++;
17+
} else {
18+
frequencies.put(s.charAt(right), frequencies.getOrDefault(s.charAt(right), 0) + 1);
19+
right++;
20+
maxLength = Math.max(maxLength, right - left);
21+
}
22+
}
23+
24+
return maxLength;
25+
}
26+
}

0 commit comments

Comments
 (0)