标签:java dup order empty turn solution example frequency return
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input:"bcabc"
Output:"abc"
Example 2:
Input:"cbacdcbc"
Output:"acdb"
https://leetcode.com/problems/remove-duplicate-letters/discuss/128235/Java-Stack
class Solution { public String removeDuplicateLetters(String s) { if(s.length() <= 1) return s; Stack<Character> stack = new Stack(); int[] freq = help(s); for(char c : s.toCharArray()){ freq[c - ‘a‘]--; if(stack.contains(c)) continue; while(!stack.isEmpty() && stack.peek() > c && freq[stack.peek() - ‘a‘] > 0) stack.pop(); stack.push(c); } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.reverse().toString(); // return sb.toString(); } public int[] help(String s){ int[] res = new int[26]; for(char c : s.toCharArray()){ res[c - ‘a‘]++; } return res; } }
巧妙,先存所有的frequency,然后遍历string,先ferq--,
然后检查是否已经存在,
然后如果stack顶元素大于当前元素,我们肯定不希望这样,然后就检查后面还有没有这个大的,有的话就pop栈顶元素。
最后用stringbuilder输出。
标签:java dup order empty turn solution example frequency return
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11909342.html