leetcode单调栈数组-数组去重

import java.util.Stack;

/**
<p>给你一个字符串 <code>s</code> ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 <strong>返回结果的字典序最小</strong>(要求不能打乱其他字符的相对位置)。</p>

<p>&nbsp;</p>

<p><strong>示例 1:</strong></p>

<pre>
<strong>输入:</strong><code>s = "bcabc"</code>
<strong>输出<code>:</code></strong><code>"abc"</code>
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>输入:</strong><code>s = "cbacdcbc"</code>
<strong>输出:</strong><code>"acdb"</code></pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> 由小写英文字母组成</li>
</ul>

<p>&nbsp;</p>

<p><strong>注意:</strong>该题与 1081 <a href="https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters">https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters</a> 相同</p>
<div><div>Related Topics</div><div><li>栈</li><li>贪心</li><li>字符串</li><li>单调栈</li></div></div><br><div><li>👍 715</li><li>👎 0</li></div>
*/

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public String removeDuplicateLetters(String s) {
        Stack<Character> stack = new Stack<>();

        //记录每个字符出现次数,后续排序会用到
        int[] count =new int[256];
        for(Character c :s.toCharArray()){
            count[c]++;
        }

        boolean[] inStack = new boolean[256];
        for(Character c :s.toCharArray()){

            count[c]--;
            if(inStack[c]==true){
                continue;
            }

            //为了条件三的排序
            //会把只出现一次 且排序靠后的给去掉
            while(!stack.isEmpty() && stack.peek()>c){

                if(count[stack.peek()]==0){
                    break;
                }

                inStack[stack.peek()]=false;
                stack.pop();
            }

            stack.push(c);
            inStack[c]= true;
        }
        StringBuffer sb = new StringBuffer();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}
//leetcode submit region end(Prohibit modification and deletion)


posted @   小傻孩丶儿  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2021-04-28 jmeter-emqtt测试环境构建
2020-04-28 sec项目启动问题
2020-04-28 Lc35_搜索插入位置
2020-04-28 设计模式六大原则
点击右上角即可分享
微信分享提示