题目:
我的解法:参考官方题解——贪心+栈
class Solution {
public String removeDuplicateLetters(String s) {
// 记录字母剩余的个数
int[] num = new int[26];
// 记录字母是否存在与栈中
boolean[] exist = new boolean[26];
int d = s.length();
for(int i=0; i<d; i++){
char c = s.charAt(i);
num[c-'a']++;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<d; i++){
char c = s.charAt(i);
if(!exist[c-'a']){
// 如果出现了当前字母比栈顶字母的字典序小时
while(sb.length() > 0 && c < sb.charAt(sb.length()-1)){
// 判断栈顶字母在后面是否还有剩余,如果有则删除栈顶字母;如果没有剩余则跳过,
// 因为要保证每个字母至少保留一个在栈中
if(num[sb.charAt(sb.length()-1)-'a']>0){
exist[sb.charAt(sb.length()-1)-'a']=false;
sb.deleteCharAt(sb.length()-1);
}else{
break;
}
}
// 将当前字母放入栈顶
sb.append(c);
exist[c-'a']=true;
}
num[c-'a']--;
}
return sb.toString();
}
}
class Solution {
public String removeDuplicateLetters(String s) {
boolean[] vis = new boolean[26];
int[] num = new int[26];
for (int i = 0; i < s.length(); i++) {
num[s.charAt(i) - 'a']++;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (!vis[ch - 'a']) {
while (sb.length() > 0 && sb.charAt(sb.length() - 1) > ch) {
if (num[sb.charAt(sb.length() - 1) - 'a'] > 0) {
vis[sb.charAt(sb.length() - 1) - 'a'] = false;
sb.deleteCharAt(sb.length() - 1);
} else {
break;
}
}
vis[ch - 'a'] = true;
sb.append(ch);
}
num[ch - 'a'] -= 1;
}
return sb.toString();
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-duplicate-letters/solution/qu-chu-zhong-fu-zi-mu-by-leetcode-soluti-vuso/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。