leetcode 316. Remove Duplicate Letters

题目

:Given a string s, 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: s = “bcabc”
Output: “abc”
Example 2:

Input: s = “cbacdcbc”
Output: “acdb”

思路1: 贪心算法,先统计每次字母出现的次数;
在保证所有字母都出现一次的情况下,将字典序最小的字母放在最前面

 public static String removeDuplicateLetters(String s) {
        if(s.length() == 0) {
            return "";
        }
        int[] letterTimes = new int[26];
        for (char letter :
                s.toCharArray()) {
            letterTimes[letter - 'a']++;
        }
        int smallestLetterPos = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) < s.charAt(smallestLetterPos)) {
                smallestLetterPos = i;
            }
            //当前字母只出现过一次,必须选取
            if (letterTimes[s.charAt(i) - 'a'] == 1) {
                break;
            }
            // 注意这里有个隐含条件, i始终是大于等于smallestLetterPos的,意味着我们当前的选取是从 smallestLetterPos 到 i
            letterTimes[s.charAt(i) - 'a']--;     //  该字母被选取了一次
        }
        // 最后记得要去掉单词中多余的位置=smallestLetterPos的字母
        return s.charAt(smallestLetterPos) + removeDuplicateLetters(s.substring(smallestLetterPos + 1).replaceAll("" + s.charAt(smallestLetterPos), ""));
    }

思路2: 单调栈,先统计每次字母出现的次数;
在保证所有字母都出现一次的情况下,在每个元素(字母)进站时,若当前字母字典序小于栈顶且栈顶元素后面还会出现, 将栈顶元素弹出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值