【LeetCode】316. Remove Duplicate Letters 去除重复字母(Medium)(JAVA)

【LeetCode】316. Remove Duplicate Letters 去除重复字母(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of lowercase English letters.

题目大意

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

注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同

解题方法

  1. 找出第一个字符:先把所有字符的出现次数用一个 count 数组记录下来
  2. 然后再从头开始遍历,记录下当前位置之前最小的字符的位置 min ,每次遍历过 count–,知道当前 count[k] == 0,说明这个字符后面没有了,也就是这个字符必须放在这之前,不能再被去除了
  3. min 位置就是第一个要找出的字符,min 之前的都没有了,之后只需要 min 往后找即可,而且 min 位置的字符也不需要再找了
class Solution {
    public String removeDuplicateLetters(String s) {
        if (s.length() <= 1) return s;

        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        int min = 0;
        for (int i = 0; i < s.length(); i++) {
            char temp = s.charAt(i);
            if (temp < s.charAt(min)) min = i;
            count[temp - 'a']--;
            if (count[temp - 'a'] == 0) break;
        }
        return s.charAt(min) + removeDuplicateLetters(s.substring(min + 1).replaceAll("" + s.charAt(min), ""));
    }
}

执行耗时:30 ms,击败了5.43% 的Java用户
内存消耗:39.4 MB,击败了6.07% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值