Leetcode 316.去除重复字母

本文介绍了一种去除字符串中重复字母的算法,确保每个字母只出现一次,并保持字典序最小。通过递归处理,选择左边界字母,移除左侧所有字母及自身,再递归解决剩余子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

去除重复字母

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

示例 1:

输入: "bcabc"

输出: "abc"

示例 2:

输入: "cbacdcbc"

输出: "acdb"

 

Given the string s, the greedy choice (i.e., the leftmost letter in the answer) is the smallest s[i], s.t. the suffix s[i .. ] contains all the unique letters. (Note that, when there are more than one smallest s[i]'s, we choose the leftmost one. Why? Simply consider the example: "abcacb".)

 

After determining the greedy choice s[i], we get a new string s' from s by

 

removing all letters to the left of s[i],

removing all s[i]'s from s.

 

We then recursively solve the problem w.r.t. s'.

 

The runtime is O(26 * n) = O(n).

 

 1 public class Solution{
 2     public String removeDuplicateLetters(String s){
 3         int[] cnt=new int[26];
 4         int pos=0;
 5         for(int i=0;i<s.length();i++) cnt[s.charAt(i)-'a']++;
 6         for(int i=0;i<s.length();i++){
 7             if(s.charAt(i)<s.charAt(pos)){
 8                 pos=i;
 9             }
10             if(--cnt[s.charAt(i)-'a']==0){
11                 break;
12             }
13         }
14         return s.length()==0?"":s.charAt(pos)+removeDuplicateLetters(s.substring(pos+1).replaceAll(""+s.charAt(pos),""));
15     }
16 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值