File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ input : String s
3
+ output: length of the longest substring without repeating chararcters
4
+
5
+ example)
6
+
7
+ abccba >> abc, cba >> 3
8
+ abcdeffg >> abcdef >> 6
9
+ constraints
10
+ 1) length of string s?
11
+ [0, 5 * 10^4]
12
+ 2) alphanumeric characters?
13
+ english, digit, symbol, space. >> 256 ascii characters
14
+ else >> hashmap
15
+
16
+ solution1)
17
+
18
+ iterate through string from index i = 0 to n-1
19
+ iterate through string s from index j = i + 1, j to n
20
+ if duplicate character comes up, then compare length
21
+ tc : O(n^2)
22
+ sc : O(1)
23
+
24
+ solution 2) sliding window
25
+
26
+ ds : array or hashmap << when character range is ascii, we can use array instead
27
+
28
+ use two pointer l and r
29
+ read until there is no repeating character in range [l, r]
30
+ if duplicate exists
31
+ move l until every character is unique
32
+ ex)
33
+
34
+ abaabcdef
35
+ l
36
+ r
37
+ ^^ ^
38
+ tc : O(n)
39
+ sc : O(1)
40
+
41
+
42
+ */
43
+
44
+ class Solution {
45
+ public int lengthOfLongestSubstring (String s ) {
46
+ int [] freq = new int [256 ];
47
+ int l = 0 , r = 0 ;
48
+ int n = s .length ();
49
+ int maxLength = 0 ;
50
+ if (n <= 1 ) return n ;
51
+
52
+ while (r < n && l <= r ) {
53
+ char curC = s .charAt (r );
54
+ freq [curC ]++;
55
+ while (l < r && freq [curC ] > 1 ) {
56
+ char prevC = s .charAt (l );
57
+ freq [prevC ]--;
58
+ l ++;
59
+ }
60
+ maxLength = Math .max (maxLength , r - l + 1 );
61
+ r ++;
62
+ }
63
+ maxLength = Math .max (maxLength , r - l );
64
+ return maxLength ;
65
+ }
66
+ }
You can’t perform that action at this time.
0 commit comments