給你一個字符串 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();}
}