LeetCode 题解工作台

不同字符的最小子序列

返回 s 字典序最小的 子序列 ,该子序列包含 s 的所有不同字符,且只包含一次。 示例 1: 输入: s = "bcabc" 输出 : "abc" 示例 2: 输入: s = "cbacdcbc" 输出: "acdb" 提示: 1 s 由小写英文字母组成 注意: 该题与 316 https://l…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

我们用一个数组 记录字符串 每个字符最后一次出现的位置,用栈来保存结果字符串,用一个数组 或者一个整型变量 记录当前字符是否在栈中。 遍历字符串 ,对于每个字符 ,如果 不在栈中,我们就需要判断栈顶元素是否大于 ,如果大于 ,且栈顶元素在后面还会出现,我们就将栈顶元素弹出,将 压入栈中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

返回 s 字典序最小的子序列,该子序列包含 s 的所有不同字符,且只包含一次。

 

示例 1:

输入:s = "bcabc"
输出"abc"

示例 2:

输入:s = "cbacdcbc"
输出:"acdb"

 

提示:

  • 1 <= s.length <= 1000
  • s 由小写英文字母组成

 

注意:该题与 316 https://leetcode.cn/problems/remove-duplicate-letters/ 相同

lightbulb

解题思路

方法一:栈

我们用一个数组 lastlast 记录字符串 ss 每个字符最后一次出现的位置,用栈来保存结果字符串,用一个数组 visvis 或者一个整型变量 maskmask 记录当前字符是否在栈中。

遍历字符串 ss,对于每个字符 cc,如果 cc 不在栈中,我们就需要判断栈顶元素是否大于 cc,如果大于 cc,且栈顶元素在后面还会出现,我们就将栈顶元素弹出,将 cc 压入栈中。

最后将栈中元素拼接成字符串作为结果返回。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def smallestSubsequence(self, s: str) -> str:
        last = {c: i for i, c in enumerate(s)}
        stk = []
        vis = set()
        for i, c in enumerate(s):
            if c in vis:
                continue
            while stk and stk[-1] > c and last[stk[-1]] > i:
                vis.remove(stk.pop())
            stk.append(c)
            vis.add(c)
        return "".join(stk)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for a solution that efficiently uses a stack to maintain order.

  • question_mark

    Ensure that the candidate tracks character occurrences and pops characters from the stack when appropriate.

  • question_mark

    Candidates should avoid brute-force solutions and focus on a greedy, stack-based approach.

warning

常见陷阱

外企场景
  • error

    Failing to check if a character can still appear later, which can result in an incorrect subsequence.

  • error

    Not managing the stack in lexicographical order, leading to suboptimal solutions.

  • error

    Inefficient handling of character occurrences, which may lead to unnecessary operations and higher time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handle the case where the string contains all unique characters.

  • arrow_right_alt

    Optimize for strings with large character repetitions.

  • arrow_right_alt

    Extend the solution to handle strings with uppercase letters or non-alphabetic characters.

help

常见问题

外企场景

不同字符的最小子序列题解:栈·状态 | LeetCode #1081 中等