给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
示例 1:
输入:s = “bcabc”
输出:”abc”
示例 2:
输入:s = “cbacdcbc”
输出:”acdb”
提示:
1 <= s.length <= 104
s 由小写英文字母组成
class Solution {public String removeDuplicateLetters(String s) {char[] ch = s.toCharArray();int n = ch.length;int[] cnts = new int[26];for (int i = 0; i < n; ++i) cnts[ch[i] - 'a'] = i;StringBuilder res = new StringBuilder();res.append("a");//判重,判断当前单调栈里面是否有这个元素boolean[] visited = new boolean[26];for (int i = 0; i < n; ++i) {int len = res.length();//如果有就跳过if (visited[ch[i] - 'a']) continue;//当栈顶元素后面还会出现时,并且当前元素比栈顶字序小则弹出while (cnts[res.charAt(len - 1) - 'a'] > i && ch[i] < res.charAt(len - 1)) {len --;visited[res.charAt(len) - 'a'] = false;}//删除掉if (len < res.length()) res.delete(len, res.length());res.append(ch[i]);visited[ch[i] - 'a'] = true;}res.delete(0, 1);return res.toString();}}
