File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashSet ;
2
+ import java .util .Set ;
3
+
4
+ /*
5
+ * @lc app=leetcode id=3 lang=java
6
+ *
7
+ * [3] Longest Substring Without Repeating Characters
8
+ *
9
+ * https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
10
+ *
11
+ * algorithms
12
+ * Medium (27.96%)
13
+ * Total Accepted: 849.6K
14
+ * Total Submissions: 3M
15
+ * Testcase Example: '"abcabcbb"'
16
+ *
17
+ * Given a string, find the length of the longest substring without repeating
18
+ * characters.
19
+ *
20
+ *
21
+ * Example 1:
22
+ *
23
+ *
24
+ * Input: "abcabcbb"
25
+ * Output: 3
26
+ * Explanation: The answer is "abc", with the length of 3.
27
+ *
28
+ *
29
+ *
30
+ * Example 2:
31
+ *
32
+ *
33
+ * Input: "bbbbb"
34
+ * Output: 1
35
+ * Explanation: The answer is "b", with the length of 1.
36
+ *
37
+ *
38
+ *
39
+ * Example 3:
40
+ *
41
+ *
42
+ * Input: "pwwkew"
43
+ * Output: 3
44
+ * Explanation: The answer is "wke", with the length of 3.
45
+ * Note that the answer must be a substring, "pwke" is a
46
+ * subsequence and not a substring.
47
+ *
48
+ *
49
+ *
50
+ *
51
+ */
52
+ class Solution {
53
+ public int lengthOfLongestSubstring (String s ) {
54
+ int len = s .length ();
55
+ if (len < 2 ) {
56
+ return len ;
57
+ }
58
+
59
+ int max = 0 ;
60
+ Set <Character > set = new HashSet <>();
61
+
62
+ for (int fast = 0 , slow = 0 ; fast < len ; fast ++) {
63
+ while (set .contains (s .charAt (fast ))) {
64
+ set .remove (s .charAt (slow ));
65
+ slow ++;
66
+ }
67
+ set .add (s .charAt (fast ));
68
+ max = Math .max (max , fast - slow + 1 );
69
+ }
70
+
71
+ return max ;
72
+ }
73
+ }
74
+
You can’t perform that action at this time.
0 commit comments