Skip to content

Commit 620e326

Browse files
authored
Added Problem 3
1 parent 57100c6 commit 620e326

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+
// id: 3
2+
// Name: Longest Substring Without Repeating Characters
3+
// link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
4+
// Difficulty: Medium
5+
6+
class Solution {
7+
public int lengthOfLongestSubstring(String s) {
8+
int max = 0;
9+
10+
Map<Character, Integer> lastOccurrence = new HashMap<>();
11+
12+
int prev = 0;
13+
for (int current = 0; current < s.length(); current++) {
14+
// if last occurrence of current is before `prev`, then greater will be considered.
15+
16+
// like abba
17+
// at index 3, last occurrence of a is 0, but 1 will be considered.
18+
19+
// there will be distinct characters from in [prev, current]
20+
prev = Math.max(lastOccurrence.getOrDefault(s.charAt(current), prev), prev);
21+
22+
max = Math.max(current-prev+1, max);
23+
lastOccurrence.put(s.charAt(current), current+1);
24+
}
25+
return max;
26+
}
27+
}

0 commit comments

Comments
 (0)