LeetCode: 316. Remove Duplicate Letters

本文介绍了解决LeetCode上编号为316的问题“Remove Duplicate Letters”的方法。该问题要求从给定的仅包含小写字母的字符串中移除重复的字母,确保每个字母只出现一次,并且结果字符串在字典序中是最小的。文章提供了详细的解题思路和AC代码实现。

LeetCode: 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"

解题思路

  1. 先保证每个元素都出现一次
  2. 再在前面选取最小的元素作为新串的首字母
  3. 递归对非首字母的子串做同样的处理

AC 代码


func removeLetters(s string, idx int, ch byte) string {
    for i := idx; i < len(s); i++ {
        if s[i] == ch {
            s = s[:i] + s[i+1:]
            i--
        }
    }
    
    return s
}

func removeDuplicateLetters(s string) string {
    var flags [26]bool
    alpNum := 0

    for i := 0; i < len(s); i++ {
        if flags[s[i]-'a'] == false {
            alpNum++
        }
        flags[s[i]-'a'] = true
    }
    if len(s) == alpNum {
        return s
    }
    
    // 先保证每个元素都出现一次
    first := -1
    for i := len(s)-1; i >= 0; i-- {
        if alpNum == 0 {
            break
        }
        if flags[s[i]-'a'] == true {
            alpNum--
            first = i
            flags[s[i]-'a'] = false
        }
    }
    
    
    // 再在前面选取最小的元素
    min := 0
    for i := 1; i <= first; i++ {
        if s[min] > s[i] {
            min = i
        }
    }
    
    // 删除后面的 min
    s = removeLetters(s, min+1, s[min])
    
    return s[min:min+1]+removeDuplicateLetters(s[min+1:])
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值