316. Remove Duplicate Letters
2026/1/12小于 1 分钟约 285 字
316. Remove Duplicate Letters
难度: Medium
题目描述
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.
Example 1:
Input: s = "bcabc" Output: "abc"
Example 2:
Input: s = "cbacdcbc" Output: "acdb"
Constraints:
1 <= s.length <= 104sconsists of lowercase English letters.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
解题思路
代码实现
解决方案
java
import java.util.LinkedList;
class Solution {
public String removeDuplicateLetters(String s) {
boolean[] vis = new boolean[26];
int[] num = new int[26];
for (int i = 0; i < s.length(); i++) {
num[s.charAt(i) - 'a']++;
}
LinkedList<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (stack.isEmpty()) {
stack.push(ch);
vis[ch - 'a'] = true;
num[s.charAt(i) - 'a']--;
} else {
if (!vis[ch - 'a']) {
while (!stack.isEmpty() && stack.peek() > ch && num[stack.peek() - 'a'] > 0) {
vis[stack.peek() - 'a'] = false;
stack.pop();
}
stack.push(ch);
vis[ch - 'a'] = true;
num[s.charAt(i) - 'a']--;
}else{
num[s.charAt(i) - 'a']--;
}
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}