Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
</pre><pre name="code" class="csharp">
</pre><pre name="code" class="csharp">
</pre><pre name="code" class="csharp">public class Solution {
public string RemoveDuplicateLetters(string s) {
Dictionary<char, int>cnts = new Dictionary<char,int>();
Stack<char>stk = new Stack<char>();
string ret = string.Empty;
List<bool>isVisited = new List<bool>();
for(int i = 0; i < 26; i++)
isVisited.Add(false);
foreach(var each in s)
{
if(cnts.ContainsKey(each))
cnts[each]++;
else cnts.Add(each, 1);
}
for(int i = 0; i < s.Length; cnts[s[i]]--, i++)
{
if((isVisited[s[i] - 'a']) || ((stk.Count() > 0)&& (stk.Peek() == s[i])))
{
continue;
}
while((stk.Count() > 0) && (stk.Peek() > s[i]) && (cnts[stk.Peek()] > 0))
{
isVisited[stk.Peek() - 'a'] =false;
stk.Pop();
}
stk.Push(s[i]);
isVisited[s[i] - 'a'] = true;
}
while(stk.Count() > 0)
{
ret += stk.Peek();
stk.Pop();
}
int len = ret.Length;
string result = string.Empty;
for(int i = len - 1; i >= 0; i--)
{
result += ret[i];
}
return result;
}