-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestSubstring.cs
77 lines (62 loc) · 1.71 KB
/
LongestSubstring.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Text;
namespace LeetCodeTests;
public class LongestSubstring
{
public int LengthOfLongestSubstring(string s, out string foundString)
{
var act = 0;
var maxLength = -1;
var foundDict = new Dictionary<char, int>();
foundString = string.Empty;
while (act < s.Length)
{
var c = s[act++];
if (!foundDict.TryGetValue(c,out var found))
{
foundDict[c] = act;
}
else
{
if (foundDict.Keys.Count >= maxLength)
{
maxLength = foundDict.Keys.Count;
foundString = FoundToString(foundDict);
}
foundDict.Clear();
act = found;
}
}
return maxLength;
}
public int LengthOfLongestSubstringSpan(string s)
{
var act = 0;
var maxLength = -1;
var foundDict = new Dictionary<char, int>();
var span = s.AsSpan();
while (act < span.Length)
{
var c = span[act++];
if (!foundDict.TryGetValue(c, out var found))
{
foundDict[c] = act;
if (foundDict.Keys.Count > maxLength) maxLength = foundDict.Keys.Count;
}
else
{
foundDict.Clear();
act = found;
}
}
return maxLength;
}
private string FoundToString(Dictionary<char, int> dict)
{
var sb = new StringBuilder();
foreach (var key in dict.Keys)
{
sb.Append(key);
}
return sb.ToString();
}
}