题目
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
示例1:
输入:s = “bcabc”
输出:“abc”
示例2:
输入:s = “cbacdcbc”
输出:“acdb”
思路
使用LinkedList模拟一个栈,使用一个count数组来记录字符串中每个字符出现的次数。然后对字符串开始遍历,如果该字符不在栈中,那么便把他与栈顶字符进行比较,如果他的字典序比栈顶字符小,并且栈顶字符后面还出现过,那么就弹出栈顶元素,循环判断。
代码
public String removeDuplicateLetters(String s) {
// 用于模拟栈
LinkedList<Character> list = new LinkedList<>();
// 用于记录每个字符的出现次数
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c-'a']++;
}
for (int i = 0; i < s.length(); i++) {
char tmp = s.charAt(i);
// 如果该字符不在list中
if (!list.contains(tmp)){
// 如果该字符的字典序比栈顶的字符小,并且栈顶的字符后面还会出现,
// 那么便弹出该元素
while (!list.isEmpty()&&list.getLast()>tmp
&&count[list.getLast()-'a']>0){
list.removeLast();
}
list.addLast(tmp);
}
// 当前字符数量减一
count[tmp-'a']--;
}
StringBuilder sb = new StringBuilder();
for (Character c: list) {
sb.append(c);
}
return sb.toString();
}