微信漫画网站模板,邢台见贤网络科技有限公司,管理软件erp,建立网站大概投入给你一个字符串 s #xff0c;请你去除字符串中重复的字母#xff0c;使得每个字母只出现一次。需保证 返回结果的字典序最小#xff08;要求不能打乱其他字符的相对位置#xff09;。
注意#xff1a;该题与 1081 https://leetcode-cn.com/problems/smallest-subsequenc…给你一个字符串 s 请你去除字符串中重复的字母使得每个字母只出现一次。需保证 返回结果的字典序最小要求不能打乱其他字符的相对位置。
注意该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1
输入s “bcabc” 输出“abc”
代码
class Solution {public String removeDuplicateLetters(String s) {int ns.length();int[] cntnew int[26];SetCharacter setnew HashSet();for(int i0;in;i)//记录每个字母对应的个数{cnt[s.charAt(i)-a];}LinkedListCharacter linkedListnew LinkedList();for(int i0;in;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 stringBuildernew StringBuilder();for(Character c:linkedList) stringBuilder.append(c);return stringBuilder.toString();}
}