题目
: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.
Example 1:
Input: s = “bcabc”
Output: “abc”
Example 2:
Input: s = “cbacdcbc”
Output: “acdb”
思路1: 贪心算法,先统计每次字母出现的次数;
在保证所有字母都出现一次的情况下,将字典序最小的字母放在最前面
public static String removeDuplicateLetters(String s) {
if(s.length() == 0) {
return "";
}
int[] letterTimes = new int[26];
for (char letter :
s.toCharArray()) {
letterTimes[letter - 'a']++;
}
int smallestLetterPos = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < s.charAt(smallestLetterPos)) {
smallestLetterPos = i;
}
//当前字母只出现过一次,必须选取
if (letterTimes[s.charAt(i) - 'a'] == 1) {
break;
}
// 注意这里有个隐含条件, i始终是大于等于smallestLetterPos的,意味着我们当前的选取是从 smallestLetterPos 到 i
letterTimes[s.charAt(i) - 'a']--; // 该字母被选取了一次
}
// 最后记得要去掉单词中多余的位置=smallestLetterPos的字母
return s.charAt(smallestLetterPos) + removeDuplicateLetters(s.substring(smallestLetterPos + 1).replaceAll("" + s.charAt(smallestLetterPos), ""));
}
思路2: 单调栈,先统计每次字母出现的次数;
在保证所有字母都出现一次的情况下,在每个元素(字母)进站时,若当前字母字典序小于栈顶且栈顶元素后面还会出现, 将栈顶元素弹出。