-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubStringWithoutRepeatingCharacter.java
More file actions
108 lines (71 loc) · 2.56 KB
/
Copy pathLongestSubStringWithoutRepeatingCharacter.java
File metadata and controls
108 lines (71 loc) · 2.56 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
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.
*/
package leetcode;
import java.util.HashSet;
import java.util.Set;
/*
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
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.
*/
public class LongestSubStringWithoutRepeatingCharacter {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if (n == 0) return 0;
int maxLength = 0;
int left = 0;
Set<Character> seenChars = new HashSet<>();
for (int right = 0; right < n; right++) {
while (seenChars.contains(s.charAt(right))) {
seenChars.remove(s.charAt(left));
left++;
}
seenChars.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
public static void main(String[] args) {
LongestSubStringWithoutRepeatingCharacter solution = new LongestSubStringWithoutRepeatingCharacter();
// Test cases
String s1 = "abcabcbb";
String s2 = "bbbbb";
String s3 = "pwwkew";
System.out.println("Longest substring length for \"" + s1 + "\": " + solution.lengthOfLongestSubstring(s1)); // Output: 3
System.out.println("Longest substring length for \"" + s2 + "\": " + solution.lengthOfLongestSubstring(s2)); // Output: 1
System.out.println("Longest substring length for \"" + s3 + "\": " + solution.lengthOfLongestSubstring(s3)); // Output: 3
}
}