leetcode316 去除重复字母

时间:2021-09-05
本文章向大家介绍leetcode316 去除重复字母,主要包括leetcode316 去除重复字母使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

思路:

贪心 + 单调栈。

实现:

 1 class Solution
 2 {
 3 public:
 4     string removeDuplicateLetters(string s)
 5     {
 6         int n = s.length();
 7         stack<char> st;
 8         vector<int> cnt(26, 0);
 9         for (int i = 0; i < n; i++)
10         {
11             cnt[s[i] - 'a']++;
12         }
13         vector<bool> vis(26, false);
14         for (int i = 0; i < n; i++)
15         {
16             if (vis[s[i] - 'a']) { cnt[s[i] - 'a']--; continue; }
17             while (!st.empty() and s[i] <= st.top() and cnt[st.top() - 'a'] > 1)
18             {
19                 cnt[st.top() - 'a']--;
20                 vis[st.top() - 'a'] = false;
21                 st.pop();
22             }
23             st.push(s[i]);
24             vis[s[i] - 'a'] = true;
25         }
26         string res = "";
27         while (!st.empty()) { res += st.top(); st.pop(); }
28         reverse(res.begin(), res.end());
29         return res;
30     }
31 };

原文地址:https://www.cnblogs.com/wangyiming/p/15228920.html