LeetCode-Remove Duplicate Letters

本文介绍了一种去除字符串中重复字符并保持最小字典序的算法。通过维护一个有效字符列表,并迭代整个字符串,确保每次添加的新字符尽可能地靠前排列。文章详细解释了算法逻辑,并提供了完整的Java实现代码。

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

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example:

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

Analysis:

We maintain a smallest valid char list and iterate through the whole string. When we move to the next char, we want to put it as ahead as possible in the valid char list so we want to remove all chars that are larger than it straing from the tail, e.g., "acd" and the next char is 'b', we then want to put it after 'a'; however, whether we can remove 'd' and 'c' depends on whether there are still 'b' and 'c' in the left string, if yes, then we can safely remove them.

Also, if we cannot remove 'd', then we cannot remove any chars in front of 'd', because this will actually enlarge the lexicographical order. e.g., "acd" and the following is "bc", if we remove "c", then the result is "adbc" which is larger than "acdb".

 

Solution:

 1 public class Solution {
 2     public String removeDuplicateLetters(String s) {
 3         if (s.length() == 0)
 4             return s;
 5 
 6         int[] charCount = new int[26];
 7         boolean[] inStack = new boolean[26];
 8         Arrays.fill(charCount, 0);
 9         Arrays.fill(inStack, false);
10         char[] charArray = s.toCharArray();
11         for (char c : charArray) {
12             charCount[c - 'a']++;
13         }
14 
15         Stack<Character> resStack = new Stack<Character>();
16         for (char c : charArray) {
17             int index = c - 'a';
18             charCount[index]--;
19             
20             if (inStack[index])
21                 continue;
22 
23             while (!resStack.isEmpty() && resStack.peek() > c && charCount[resStack.peek() - 'a'] > 0) {
24                 inStack[resStack.pop() - 'a'] = false;
25             }
26 
27             resStack.push(c);
28             inStack[index] = true;
29         }
30 
31         StringBuilder builder = new StringBuilder();
32         while (!resStack.isEmpty()) {
33             builder.append(resStack.pop());
34         }
35         return builder.reverse().toString();
36     }
37 }

 

转载于:https://www.cnblogs.com/lishiblog/p/5684495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值