leetcode 316. 去除重复字母 栈(类似单调栈) + 贪心

给你一个仅包含小写字母的字符串,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

示例 1:

输入: “bcabc”
输出: “abc”

示例 2:

输入: “cbacdcbc”
输出: “acdb”

注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
通过次数20,178
提交次数48,928

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-letters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


题意:给定一个字符串并对其进行去重,要求去重后字典序最小

看了题解才知道具体做法就是

  • 枚举每个字符s[i]入栈
  • s[i]入栈前,如果栈顶top如果往后还有,且top大于s[i]则把top退栈

具体证明在评论区@欧阳卫平大佬给出了,记录学习一下
在这里插入图片描述

// #define debug
#ifdef debug
#include <time.h>
#include "win_majiao.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
typedef vector<vector<int> > VVI;

using namespace std;

#define show(x...) \
	do { \
	cout << "\033[31;1m " << #x << " -> "; \
	err(x); \
	} while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
	inline void read(T &x, T2 &... oth) {
		x = 0;
		char ch = getchar();
		ll f = 1;
		while (!isdigit(ch)) {
			if (ch == '-') f *= -1; 
			ch = getchar();
		}
		while (isdigit(ch)) {
			x = x * 10 + ch - 48;
			ch = getchar();
		}
		x *= f;
		read(oth...);
	}
	template <typename T, typename... T2>
	inline void print(T x, T2... oth) {
		ll p3=-1;
		if(x<0) putchar('-'), x=-x;
		do{
				print_f[++p3] = x%10 + 48;
		} while(x/=10);
		while(p3>=0) putchar(print_f[p3--]);
		putchar(' ');
		print(oth...);
	}
} // namespace FastIO
using FastIO::print;
using FastIO::read;


class Solution {
public:
    string removeDuplicateLetters(string s) {
        string ans;
		int cnt[128] = { 0 }, n = s.length();
		for(auto ch : s) cnt[ch] ++;
		int instk[128] = { 0 };
		for(int i=0; i<n; i++) {
			char ch = s[i];
			cnt[ch] --;
			if(instk[ch]) continue ;
			while(!ans.empty() && cnt[ans.back()] && ch<ans.back()) {
				instk[ans.back()] = false;
				ans.pop_back();
			}
			ans.push_back(ch);
			instk[ch] = true;
		}
		return ans;
    }
};

#ifdef debug
signed main() {
	Solution s;
	string str = "cbacdcbc";
	cout << s.removeDuplicateLetters(str) << endl;


	return 0;
}
#endif

java代码

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

class Solution {
    public String removeDuplicateLetters(String s) {
        char[] ch = s.toCharArray();
        Stack<Character> stk = new Stack<>();
        int cnt[] = new int[128];
        boolean instk[] = new boolean[128];
        for(int i=0; i<ch.length; i++) cnt[ch[i]] ++;

        for(int i=0; i<ch.length; i++) {
            cnt[ch[i]] --;
            if(instk[ch[i]]) continue ;
            while(!stk.empty() && stk.peek()>ch[i] && cnt[stk.peek()]>0) {
                Character pop = stk.pop();
                instk[pop] = false;
            }
            instk[ch[i]] = true;
            stk.push(ch[i]);
        }

        char ans[] = new char[stk.size()];
//        System.out.println(stk);
        for(int i=stk.size()-1; i>=0; i--) ans[i] = stk.pop();
        return new String(ans);
    }
}

public class Main {
    public static final boolean debug = true;
    public static String INPATH = "C:\\Users\\majiao\\Desktop\\test.txt",
            OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
    public static StreamTokenizer tok;
    public static BufferedReader cin;
    public static PrintWriter cout;

    public static long start_time = 0, out_time = 0;
    public static int n, m, K, Q, MAXN = (int)1e5+7, INF = 0x3f3f3f3f;
    public static byte buf[] = new byte[MAXN];

    public static void main(String[] args) throws IOException {
        main_init();
        if(debug) { start_time = System.currentTimeMillis(); }
        if(false) { System.setOut(new PrintStream(OUTPATH)); }

        Solution solu = new Solution();
        String text = "cbacdcbc";
        cout.printf("%s\n", solu.removeDuplicateLetters(text));
        if(debug) {
            out_time = System.currentTimeMillis();
            cout.printf("run time : %d ms\n", out_time-start_time);
        }
        cout.flush();
    }

    public static void show(List<Object> list, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        for(Object x : list) {
            cout.printf("[%s] ", x);
        }
        cout.printf("\n");
    }

    public static void show(Map<Object, Object> mp, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        Set<Map.Entry<Object, Object>> entries = mp.entrySet();
        for (Map.Entry<Object, Object> en : entries) {
            cout.printf("[%s,%s] ", en.getKey(), en.getValue());
        }
        cout.printf("\n");
    }

    public static<T> void forarr(T arr[], int ...args) {
        int lef = 0, rig = arr.length - 1;
        if(args.length > 0) { lef = args[0]; rig = args[1]; }
        cout.printf(" : ");
        for( ; lef<=rig; lef++) {
            cout.printf("[%s] ", args[lef]);
        }
        cout.printf("\n");
    }

    public static void main_init() {
        try {
            if (debug) {
                cin = new BufferedReader(new InputStreamReader(
                        new FileInputStream(INPATH)));
            } else {
                cin = new BufferedReader(new InputStreamReader(System.in));
            }
            cout = new PrintWriter(new OutputStreamWriter(System.out));
//            cout = new PrintWriter(OUTPATH);
            tok = new StreamTokenizer(cin);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String next_str() {
        try {
            tok.nextToken();
            if (tok.ttype == StreamTokenizer.TT_EOF)
                return null;
            else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
                return String.valueOf((int)tok.nval);
            } else if (tok.ttype == StreamTokenizer.TT_WORD) {
                return tok.sval;
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int read_int() {
        String tmp_next_str = next_str();
        return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
    }
    public static long read_long() { return Long.parseLong(next_str()); }
    public static double read_double() { return Double.parseDouble(next_str()); }
    public static BigInteger read_big() { return new BigInteger(next_str()); }
    public static BigDecimal read_dec() { return new BigDecimal(next_str()); }

    class Pair implements Comparable<Pair>{
        int fst, sec;
        public Pair() { }
        public Pair(int fst, int sec) {
            this.fst = fst;
            this.sec = sec;
        }
        @Override
        public int compareTo(Pair o) {
            return fst - o.fst == 0 ? sec - o.sec : fst - o.fst;
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值