316. Remove Duplicate Letters

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了316. Remove Duplicate Letters相关的知识,希望对你有一定的参考价值。

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输出。

 

以上是关于316. Remove Duplicate Letters的主要内容,如果未能解决你的问题,请参考以下文章

316. Remove Duplicate Letters

leetcode 316. Remove Duplicate Letters

***Leetcode 316. Remove Duplicate Letters

leetcode 316 Remove Duplicate Letters

LeetCode #316 Remove-Duplicate Letters 数组 字符串

LeetCode 316. Remove Duplicate Letters(贪心)