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 1:
Input:"bcabc"Output:"abc"
Example 2:
Input:"cbacdcbc"Output:"acdb"
题解如下:
class Solution {
public String removeDuplicateLetters(String s) {
if(s == null || s.length() <= 0) {
return "";
}
char[] arr = s.toCharArray();
int[] cnt = new int[26];//用于记录每个字母出现的次数
for(char c:arr) {
cnt[c-'a']++;
}
int pos = 0;
for(int i = 0;i < arr.length;i++) {
if(arr[i] < arr[pos])
pos = i;
if(--cnt[arr[i]-'a'] == 0) {
break;
}
}
return arr[pos] + removeDuplicateLetters(s.substring(pos+1).replaceAll(arr[pos]+"",""));
}
}
本文介绍了一种去除字符串中重复字符的算法,确保结果在字典序中最小。通过使用递归和计数数组,该算法能高效地处理只包含小写字母的输入。示例包括bcabc和cbacdcbc的处理过程。

被折叠的 条评论
为什么被折叠?



