- 去除重复字母
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = “bcabc”
输出:“abc”
示例 2:
输入:s = “cbacdcbc”
输出:“acdb”
提示:
1 <= s.length <= 104
s 由小写英文字母组成
题目描述
给定一个字符串,找到字典序最小的不重复序列,要求不改变字母的相对位置。
思路
栈存结果
标志数组
计数器
先对字符串预处理,统计每个字符出现的次数,用于后面判断后面字符是否存在与当前字符相等的字符。
遍历一遍字符串:
每次对字符的出现次数减一;
如果当前字符出现在栈中,就跳过当前字符;
如果栈不空且栈顶字符字典序大于当前字符且字符串后面还有和栈顶字符相同时,栈顶元素出栈,并标记栈顶字符不存在栈中,标志位为false;
将当前字符加入栈中,置标志位位true;
最后所有元素出栈并用拼接起来,反转后即可。
class Solution {
public String removeDuplicateLetters(String s) {
Deque<Character> stack = new LinkedList<>();
int[] count = new int[26];
int n = s.length(), i;
boolean[] inStack = new boolean[26];
for (i = 0; i < n; ++ i) {
// System.out.println(s.charAt(i));
count[s.charAt(i) - 'a'] ++;
}
i = 0;
for (i = 0; i < n; ++ i) {
char c = s.charAt(i);
int index = c - 'a';
count[index] --;
if (inStack[index]) {
continue;
}
while (! stack.isEmpty() && stack.peek() > c) {
int id = stack.peek() - 'a';
// System.out.println("i: " + i + " " + stack.peek());
if (count[id] <= 0) {
break;
}
stack.pop();
inStack[id] = false;
}
stack.push(c);
inStack[index] = true;
// System.out.println(i);
}
StringBuilder sb = new StringBuilder();
while (! stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}