-
Notifications
You must be signed in to change notification settings - Fork 112
/
0316-RemoveDuplicateLetters.cs
41 lines (36 loc) · 1.19 KB
/
0316-RemoveDuplicateLetters.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
//-----------------------------------------------------------------------------
// Runtime: 84ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0316_RemoveDuplicateLetters
{
public string RemoveDuplicateLetters(string s)
{
var indexes = new Dictionary<char, int>();
for (int i = 0; i < s.Length; i++)
indexes[s[i]] = i;
var seen = new HashSet<char>();
var stack = new Stack<char>();
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (!seen.Contains(ch))
{
while (stack.Count > 0 && stack.Peek() > ch && i < indexes[stack.Peek()])
seen.Remove(stack.Pop());
seen.Add(ch);
stack.Push(ch);
}
}
var str = new char[stack.Count];
int index = stack.Count - 1;
foreach (var ch in stack)
str[index--] = ch;
return new string(str);
}
}
}