首页 > 其他 > 详细

leetcode316 去除重复字母

时间:2021-09-05 19:07:36      阅读:28      评论:0      收藏:0      [点我收藏+]

思路:

贪心 + 单调栈。

实现:

 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 };

leetcode316 去除重复字母

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!