Skip to content

Commit d075c0f

Browse files
committed
Add an optimized solution for #3 by sliding window
1 parent 5c8cd60 commit d075c0f

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/main/java/org/sean/array/LongestSubstrFinder.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.sean.array;
22

33
import java.util.HashSet;
4+
import java.util.Set;
45

56
/***
67
* 3. Longest Substring Without Repeating Characters
@@ -9,7 +10,7 @@ public class LongestSubstrFinder {
910
// "didf"
1011
// "bziuwnklhqzrxnb"
1112
// "qrsvbspk"
12-
public int lengthOfLongestSubstring(String s) {
13+
public int lengthOfLongestSubstring0(String s) {
1314
int totalLen = 0;
1415

1516
if (s.length() == 0)
@@ -60,4 +61,34 @@ else if (s.length() == 1)
6061

6162
return totalLen;
6263
}
64+
65+
Set<Character> set = new HashSet<>();
66+
67+
public int lengthOfLongestSubstring(String s) {
68+
if (s == null) return 0;
69+
if (s.length() <= 1) return s.length();
70+
71+
set.clear();
72+
73+
int max = Integer.MIN_VALUE;
74+
75+
int cnt = s.length();
76+
int i = 0;
77+
int j = i;
78+
while (i <= j && j < cnt) {
79+
char ch = s.charAt(j);
80+
81+
if (set.contains(ch)) {
82+
set.remove(s.charAt(i++));
83+
} else {
84+
set.add(ch);
85+
if (max < j - i + 1) {
86+
max = j - i + 1;
87+
}
88+
++j;
89+
}
90+
}
91+
92+
return max;
93+
}
6394
}

0 commit comments

Comments
 (0)