資料系統的基石:可靠性、可擴充套件性和可維護性+資料儲存與檢索的模型
阿新 • • 發佈:2021-12-17
給你一個字串 s ,請你去除字串中重複的字母,使得每個字母只出現一次。需保證 返回結果的字典序最小(要求不能打亂其他字元的相對位置)。
注意:該題與 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/remove-duplicate-letters
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.Scanner; import java.util.Stack; import java.util.stream.Collectors; class Solution { public String removeDuplicateLetters(String s) { boolean[] inStack = new boolean[26]; int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { cnt[s.charAt(i) - 'a']++; } Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); ++i) { if (!inStack[s.charAt(i) - 'a']) { while (!stack.isEmpty() && stack.peek() > s.charAt(i) && cnt[stack.peek() - 'a'] > 0) { inStack[stack.pop() - 'a'] = false; } stack.push(s.charAt(i)); } inStack[s.charAt(i) - 'a'] = true; cnt[s.charAt(i) - 'a']--; } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.reverse().toString(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { System.out.println(new Solution().removeDuplicateLetters(in.next())); } } }