File tree Expand file tree Collapse file tree 1 file changed +32
-1
lines changed
src/main/java/org/sean/array Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change 11package org .sean .array ;
22
33import 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}
You can’t perform that action at this time.
0 commit comments