12/20
很典型的一道单调栈题目
class Solution {
public String removeDuplicateLetters(String s) {
//记录各个字母出现的次数
int[] cnt = new int[26];
//记录各个字母在栈中是否出现过
boolean[] use = new boolean[26];
//原字符串的长度
int n = s.length();
for (int i = 0; i < n; i++) {
cnt[s.charAt(i) - 'a']++;
}
char[] stack = new char[26];
//栈顶指针
int top = -1;
for (int i = 0; i < n; i++) {
//将该字符的剩余数量-1
cnt[s.charAt(i) - 'a']--;
//如果该字符已经在栈中出现过,则不予修改
if (use[s.charAt(i) - 'a']) {
continue;
}
//退栈
//如果栈非空 并且 栈的头元素大于目前元素 并且 栈的头元素剩余个数不为0 ,进行退栈操作
while (top >= 0 && stack[top] > s.charAt(i) && cnt[stack[top] - 'a'] > 0) {
//将头元素退栈,并将头元素标记为 未使用
use[stack[top--] - 'a'] = false;
}
//将当前元素入栈
stack[++top] = s.charAt(i);
//将当前元素标记为 已使用
use[s.charAt(i) - 'a'] = true;
}
return String.valueOf(stack, 0, top + 1);
}
}