class Solution { public String removeDuplicateLetters(String s) { int[] tem = new int[26]; for (int i = 0; i < s.length(); i++) { char tems = s.charAt(i); tem[tems - 'a']++; } boolean[] visited = new boolean[26]; Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char get = s.charAt(i); while (!stack.isEmpty() && stack.peek() > get && !visited[get - 'a'] && tem[stack.peek() - 'a'] > 0) { visited[stack.peek() - 'a'] = false; stack.pop(); } if (visited[get - 'a']) { tem[get - 'a']--; continue; } visited[get - 'a'] = true; stack.push(get); tem[get - 'a']--; } StringBuilder sBuilder = new StringBuilder(); while (!stack.isEmpty()) { sBuilder.append(stack.pop()); } return sBuilder.reverse().toString(); } }帮我写完整的代码
时间: 2023-12-14 08:39:13 浏览: 94
这是一个去除字符串中重复字母的算法,下面是完整的代码实现:
```
public class Solution {
public String removeDuplicateLetters(String s) {
int[] tem = new int[26];
for (int i = 0; i < s.length(); i++) {
char tems = s.charAt(i);
tem[tems - 'a']++;
}
boolean[] visited = new boolean[26];
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char get = s.charAt(i);
while (!stack.isEmpty() && stack.peek() > get && !visited[get - 'a'] && tem[stack.peek() - 'a'] > 0) {
visited[stack.peek() - 'a'] = false;
stack.pop();
}
if (visited[get - 'a']) {
tem[get - 'a']--;
continue;
}
visited[get - 'a'] = true;
stack.push(get);
tem[get - 'a']--;
}
StringBuilder sBuilder = new StringBuilder();
while (!stack.isEmpty()) {
sBuilder.append(stack.pop());
}
return sBuilder.reverse().toString();
}
}
```
该算法的具体思路是用一个栈来维护一个字典序最小的字符串,并且保证每个字符只出现一次。对于每个字符,先判断它是否已经在栈中出现过,如果出现过,那么不需要考虑,直接跳过;否则,需要判断栈顶元素和当前元素的大小关系,如果栈顶元素大于当前元素且栈顶元素在后面还会出现,那么就需要将栈顶元素弹出,然后再判断新的栈顶元素和当前元素的大小关系,直到栈顶元素小于等于当前元素为止。最后将栈中元素弹出并倒序输出即可。
阅读全文