码迷,mamicode.com
首页 > 其他好文 > 详细

316. Remove Duplicate Letters

时间:2019-11-22 01:02:42      阅读:103      评论:0      收藏:0      [点我收藏+]

标签: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输出。

 

316. Remove Duplicate Letters

标签:java   dup   order   empty   turn   solution   example   frequency   return   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11909342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!