-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0003-longest-substring-without-repeating-characters.cs
61 lines (58 loc) · 1.5 KB
/
0003-longest-substring-without-repeating-characters.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// hashset
public class Solution
{
public int LengthOfLongestSubstring(string s)
{
int leftPointer = 0, rightPointer = 0, maxLength = 0;
HashSet<int> chars = new HashSet<int>();
while (rightPointer < s.Length)
{
char currChar = s[rightPointer];
if (chars.Contains(currChar))
{
// Move left pointer until all duplicate chars removed
chars.Remove(s[leftPointer]);
leftPointer++;
}
else
{
chars.Add(currChar);
maxLength = Math.Max(maxLength, rightPointer - leftPointer + 1);
rightPointer++;
}
}
return maxLength;
}
}
//bitmask
public class Solution
{
private Int128 ONE = 1;
public int LengthOfLongestSubstring(string s)
{
int Convert(char ch) => ch - ' ';
Int128 mask = 0;
int l = 0, r = 0, output = 0;
while (r < s.Length)
{
Int128 temp = mask ^ (ONE << Convert(s[r]));
if (temp < mask)
{
while (s[l] != s[r])
{
mask ^= ONE << Convert(s[l]);
l++;
}
mask ^= ONE << Convert(s[l]);
l++;
}
else
{
mask = temp;
output = Math.Max(output, r - l + 1);
r++;
}
}
return output;
}
}