LeetCode 316. Remove Duplicate Letters

来源:互联网 发布:广州谷得网络 编辑:程序博客网 时间:2024/05/22 02:13

In order to get the lexicographical order, we need to always update the new order once we found it is up-datable.  (This sentence actually is non-sense....)

An Example will make this clear.

Suppose we have the string "bcabc"

My first thought was to use stack, stack can absolutely keep the lexicographical order. If we found a smaller char, we pop-out the big ones. But, there is one problem. For example,

if it is the only character in this string, we can't pop-out in any case (once we pop it, it is gone :( ). A hashMap might be perfect for this then, we use a hashmap to remember the count of the character afterwards.

So, for example "bcabc", we use a hashmap to remember the counts of characters. map[b] = 2, map[c] = 2, map[a] = 1.

Let's start pushing into the stack.

1:

      stack: b

      count: map[b] = 1, map[c] = 2, map[a] = 1.

2:

      stack: b, c

      count: map[b] = 1, map[c] = 1, map[a] = 1.

3:

      stack: b, c, a (but a is smaller then b, c, and we know that there is b and c afterwards) ---> thus, we pop out b, c, and keep a in stack.

      count: map[b] = 1, map[c] = 1, map[a] = 0.

4:

      stack: a, b

      count: map[b] = 0, map[c] = 1, map[a] = 0.

5:

      stack: a, b, c

      count: map[b] = 0, map[c] = 0, map[a] = 0.   ---> done: output "abc"

#include <string>#include <stack>#include <vector>#include <iostream>#include <algorithm>using namespace std;/*  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.  Example:  Given "bcabc" --> return "abc"  Given "cbacdcbc" --> return "acdb"*/// need to check whether the stack already has it or not. If not exists, push directly.bool notExistInStack(stack<char> ascending, char a) {  if(ascending.empty()) return true;  stack<char> tmp;  while(!ascending.empty()) {    char top = ascending.top();    if(top == a) return false;    tmp.push(top);    ascending.pop();  }  while(!tmp.empty()) {    char top = tmp.top();    ascending.push(top);    tmp.pop();  }  return true;}string removeDuplicateLetters(string s) {  vector<int> map(256, 0);  for(int i = 0; i < s.size(); ++i) {    map[s[i]]++;  }  stack<char> ascending;  for(int i = 0; i < s.size(); ++i) {    while(!ascending.empty() && (ascending.top() > s[i] && map[ascending.top()] > 0)) {      map[ascending.top()]--;      ascending.pop();    }    if(notExistInStack(ascending, s[i])) {      ascending.push(s[i]);      map[s[i]]--;    }  }  string res = "";  while(!ascending.empty()) {    char top = ascending.top();    ascending.pop();    res = top + res;  }  return res;}int main(void) {  string res = removeDuplicateLetters("bcabc");  cout << res << endl;  string res_1 = removeDuplicateLetters("cbacdcbc");  cout << res_1 << endl;}
0 0
原创粉丝点击