Leetcode #316:去除重复字母

Leetcode #316:去除重复字母

题目

题干

该问题去除重复字母

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

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

示例

示例 1:
输入:s = “bcabc”
输出:“abc”

示例 2:
输入:s = “cbacdcbc”
输出:“acdb”

题解

算法思想

  • 当字典序最小时,即12341 12351 主要看4,5的位置

  • 用栈存储,当栈空时直接入栈

  • 栈不为空时,

  • 若栈中包含当前要入栈的元素直接跳到下一次循环。(结果字符串每个字符只含有一次)

  • 若当前要入栈的字母比栈顶字母大时,考虑是否栈顶元素出栈

  • 若栈顶元素在剩余字符串中仍然存在,那么就可以出栈,出栈后继续判断新的栈顶元素是否出栈。

Java

public class RemoveDuplicateLetters {

    public static String removeDuplicateLetters(String s){
        Stack<Character> stack = new Stack<Character>();
            for (int i = 0; i < s.length(); i++) {
                char c=s.charAt(i);
                if(stack.contains(c))
                    continue;
                while(!stack.isEmpty() && stack.peek()>c && s.indexOf(stack.peek(),i)!=-1)
                    stack.pop();
                stack.push(c);
            }
            char chars[]=new char[stack.size()];
            for (int i = 0; i < stack.size(); i++) {
                chars[i]=stack.get(i);
            }
            return new String(chars);
    }

    public static void main(String[] args) {
        String string = "bbcaac";
        System.out.println(removeDuplicateLetters(string));
    }
}

Python

class Solution:
    def __init__(self, s: str):
        self.s = s

    def rm_duplicate_word(self) -> str:
        stack = []
        for i in range(len(self.s)):
            if self.s[i] in stack:
                continue
            while len(stack) != 0 and stack[-1] > self.s[i] and self.s.find(stack[-1], i) != -1:
                stack.pop()
            stack.append(self.s[i])
        return ''.join(stack)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值