-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution316.cs
54 lines (45 loc) · 1.52 KB
/
Solution316.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
using System.Text;
namespace LeetCode.Solutions;
public class Solution316
{
/// <summary>
/// 316. Remove Duplicate Letters - Medium
/// <a href="https://leetcode.com/problems/remove-duplicate-letters">See the problem</a>
/// </summary>
public string RemoveDuplicateLetters(string s)
{
var charCount = new int[26]; // Frequency of each character
var inStack = new bool[26]; // Track characters in the stack
var stack = new Stack<char>();
// Count the frequency of each character
foreach (var c in s)
{
charCount[c - 'a']++;
}
foreach (var c in s)
{
// Decrement the count for the current character
charCount[c - 'a']--;
// If character is already in the stack, skip
if (inStack[c - 'a'])
{
continue;
}
// Ensure characters are in lexicographical order and each character appears once
while (stack.Count > 0 && stack.Peek() > c && charCount[stack.Peek() - 'a'] > 0)
{
inStack[stack.Pop() - 'a'] = false;
}
// Add the current character to the stack and mark it as added
stack.Push(c);
inStack[c - 'a'] = true;
}
// Build the result string from the stack
var result = new StringBuilder();
foreach (var c in stack.Reverse())
{
result.Append(c);
}
return result.ToString();
}
}