力扣 316. 去除重复字母 C++


目录

题目要求

思路

力扣提交AC代码

C++代码


题目要求

  • 删去一些重复元素
  • 保持原有顺序
  • 使字典序最小

思路

  • 遍历一个字符串 并维护一个栈
  • 如果当前字符已经再栈内就直接跳过(具体见程序)
  • 栈顶元素 > 当前元素,那么将栈顶出栈,再进栈
    • 如果这个栈顶元素是最后的幸存者,那么拒绝出栈(题目要求只能删除重复的字符)
  • 栈顶元素 < 当前元素,那么顺利入栈

如果还是看不懂...

(那就没救了)

那就看看程序吧,程序里有注释

力扣提交AC代码

class Solution {
public:
    string removeDuplicateLetters(string s) {
        vector<int> times(260, 0); //初始化 每一个字符在后续出现次数
        string sta = ""; //用string当作栈本体
        for (auto c : s) times[c] ++; //统计次数
        for (auto c : s) {
            //如果栈中已经有了,不给进,该字符次数--
            if (sta.find(c) != string::npos) {
                times[c] --;
                continue;
            }
            //栈非空           如果栈顶 > 当前元素 但是得保证必须是最后一个幸存者,才能出栈
            while(sta.size() && sta.back() > c && times[sta.back()])
                sta.pop_back();

            //新元素入栈
            sta.push_back(c);
            times[c] --; //次数--
        }
        return sta;
    }
};

另外还贴心的贴上

C++代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    string s;
    cin >> s;
    vector<int> times(260, 0); //初始化 每一个字符在后续出现次数
    string sta = ""; //用string当作栈本体
    for (auto c : s) times[c] ++; //统计次数
    for (auto c : s) {
        //如果栈中已经有了,不给进,该字符次数--
        if (sta.find(c) != string::npos) {
            times[c] --;
            continue;
        }
        //栈非空 如果栈顶 > 当前元素 但是得保证必须是最后一个幸存者,才能出栈
        while(sta.size() && sta.back() > c && times[sta.back()])
            sta.pop_back();

        //新元素入栈
        sta.push_back(c);
        times[c] --; //次数--
    }
    cout << sta;
}

题目传送门:316. 去除重复字母 - 力扣(LeetCode)

猜你喜欢

转载自blog.csdn.net/weixin_71529971/article/details/132013969