题目:
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = “bcabc”
输出:“abc”
思路:
需要保证每个字符串中出现的字母留一个下来
字母相对顺序不变
因为要相对顺序不变,就考虑栈,因为最后结果要从头输入,考虑双向栈
元素出栈的条件为栈非空,栈顶元素大于当前元素,栈顶元素后面仍存在
class Solution {
public String removeDuplicateLetters(String s) {
LinkedList<Character> deque = new LinkedList<>();
int[] count = new int[26];
boolean[]exists = new boolean[26];
// 初始化
for(char ch : s.toCharArray()){
count[ch - 'a']++;
}
// 遍历s并入栈
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (!exists[temp - 'a']){
while (!deque.isEmpty() && deque.getLast() > temp && count[deque.getLast() - 'a'] > 0){
exists[deque.getLast() - 'a'] = false;
deque.removeLast();
}
deque.add(temp);
exists[temp - 'a'] = true;
}
count[temp - 'a']--;
}
//返回
StringBuilder res = new StringBuilder();
for(char ch : deque){
res.append(ch);
}
return res.toString();
}
}