-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Substring_Without_Repeating_Characters.java
More file actions
63 lines (45 loc) · 1.53 KB
/
Copy pathLongest_Substring_Without_Repeating_Characters.java
File metadata and controls
63 lines (45 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*. PROBLEM STATEMENT:
Given a string s, find the length of the longest substring without duplicate characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces. */
import java.util.*;
class Longest_Substring_Without_Repeating_Characters {
public int lengthOfLongestSubstring(String s) {
int low = 0;
int result = 0;
int n = s.length();
HashMap<Character , Integer> map = new HashMap<>();
for(int high = 0 ; high<n; high ++){
char c = s.charAt(high);
map.put(c,map.getOrDefault(c,0)+1);
if(map.size()==(high-low+1)){
result = Math.max(result,high-low+1);
}
else{
while(map.size()<(high-low+1)){
char left = s.charAt(low);
map.put(left , map.get(left)-1);
if(map.get(left)==0){
map.remove(left);
}
low++;
}
}
}
return result;
}
}