Skip to content

Commit 7230f42

Browse files
committed
solve longest substring without repeating characters
1 parent 3ca5871 commit 7230f42

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public int lengthOfLongestSubstring(String s) {
3+
Map<Character, Integer> characters = new HashMap<>();
4+
int maxLength = 0;
5+
int length = 0;
6+
int start = 0;
7+
8+
for(int i = 0; i < s.length(); i++){
9+
if(!characters.containsKey(s.charAt(i))){
10+
characters.put(s.charAt(i), i);
11+
length++;
12+
}
13+
else{
14+
maxLength = Math.max(length, maxLength);
15+
16+
int place = characters.get(s.charAt(i));
17+
if(place < start){
18+
characters.put(s.charAt(i), i);
19+
length++;
20+
continue;
21+
}
22+
23+
length = i - place;
24+
start = place + 1;
25+
characters.put(s.charAt(i), i);
26+
}
27+
}
28+
maxLength = Math.max(length, maxLength);
29+
30+
return maxLength;
31+
}
32+
}
33+

0 commit comments

Comments
 (0)