316. Remove Duplicate Letters 🔥
Medium
Problem:
List the characters in lexicographical order, excluding duplicates.
Input: s = "ebcabc"
Output: "eabc"
Input: s = "ebcabce"
Output: "abce"
https://leetcode.com/problems/remove-duplicate-letters/
What to learn:
Similar python technique
Solution:
Recursion
Similar to divide and conquer, the size of the suffix gradually decreases, and when nothing is left, it backtracks and the results are combined.
Use a set to exclude duplicate characters and sort the input string in alphabetical order.
Separate the suffix.
If the entire set matches the suffix set, use recursion to separate them.
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
for char in sorted(set(s)):
suffix = s[s.index(char):]
if set(s) == set(suffix):
return char + self.removeDuplicateLetters(suffix.replace(char, ""))
return ""
Stack
Push the characters onto the stack in the same order as the input string.
Skip the character if it already exists in the stack.
If the current character,
char
, is lexicographically preceding the character on the stack and the character on the stack appears later in the string, remove the character from the stack.
class Solution:
def removeDuplicateLetters(s: str) -> str:
counter, stack, seen = collections.Counter(s), [], set()
for char in s:
counter[char] -= 1
if char in seen:
continue
while stack and char < stack[-1] and counter[stack[-1]] > 0:
seen.remove(stack.pop())
stack.append(char)
seen.add(char)
return "".join(stack)
Last updated