generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem2.cs
46 lines (39 loc) · 1.23 KB
/
Problem2.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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">Longest Substring Without Repeating Characters</see>.
/// </summary>
public static class Problem2
{
/// <summary>
/// Given a string s, find the length of the longest substring without repeating characters.
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="s">String to traverse.</param>
/// <returns>Length of the longest substring without repeating characters.</returns>
public static int LengthOfLongestSubstring(string s)
{
var maxLength = 0;
if (string.IsNullOrEmpty(s))
{
return maxLength;
}
var set = new HashSet<char>(26);
for (int left = 0, right = 0; right < s.Length; right++)
{
if (!set.Add(s[right]))
{
while (s[left] != s[right])
{
if (set.Remove(s[left]))
{
left++;
}
}
left++;
}
maxLength = Math.Max(maxLength, right - left);
}
return maxLength + 1;
}
}