Skip to content

Commit cdf8f8e

Browse files
committed
add: LongestSubstringWithUniqueCharsOptimized
1 parent 24efa4a commit cdf8f8e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class LongestSubstringWithUniqueCharsOptimized {
5+
public int longestSubstringWithUniqueCharsOptimized(String s) {
6+
int maxLen = 0;
7+
Map<Character, Integer> prevIndexes = new HashMap<>();
8+
int left, right;
9+
left = right = 0;
10+
while (right < s.length()) {
11+
// If a previous index of the current character is present
12+
// in the current window, it's a duplicate character in the
13+
// window.
14+
if (prevIndexes.containsKey(s.charAt(right)) && prevIndexes.get(s.charAt(right)) >= left) {
15+
// Shrink the window to exclude the previous occurrence
16+
// of this character.
17+
left = prevIndexes.get(s.charAt(right)) + 1;
18+
}
19+
// Update 'maxLen' if the current window is larger.
20+
maxLen = Math.max(maxLen, right - left + 1);
21+
prevIndexes.put(s.charAt(right), right);
22+
// Expand the window.
23+
right++;
24+
}
25+
return maxLen;
26+
}
27+
}

0 commit comments

Comments
 (0)