Skip to content

Commit d5b0c6b

Browse files
committed
feat : longest-substring-without-repeating-characters
1 parent ce3cb8e commit d5b0c6b

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
}

0 commit comments

Comments
 (0)