给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = “bcabc”
输出:“abc”
代码
class Solution {public String removeDuplicateLetters(String s) {int n=s.length();int[] cnt=new int[26];Set<Character> set=new HashSet<>();for(int i=0;i<n;i++)//记录每个字母对应的个数{cnt[s.charAt(i)-'a']++;}LinkedList<Character> linkedList=new LinkedList<>();for(int i=0;i<n;i++){ cnt[s.charAt(i)-'a']--;if(set.contains(s.charAt(i))) continue;while (!linkedList.isEmpty()&&s.charAt(i)<linkedList.getLast()&&cnt[linkedList.getLast()-'a']>=1)set.remove( linkedList.removeLast());//比当前字母大并且属于重复的元素出栈linkedList.addLast(s.charAt(i));//加入当前元素set.add(s.charAt(i));}StringBuilder stringBuilder=new StringBuilder();for(Character c:linkedList) stringBuilder.append(c);return stringBuilder.toString();}
}