给我写出完整的可运行的代码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(); }的 }
时间: 2024-01-24 19:04:11 浏览: 153
Java String源码分析并介绍Sting 为什么不可变
这里是完整可运行的代码,您可以直接复制粘贴并运行:
```
import java.util.*;
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();
}
public static void main(String[] args) {
Solution solution = new Solution();
String s = "bcabc";
String result = solution.removeDuplicateLetters(s);
System.out.println(result);
}
}
```
在这个示例中,我们调用了removeDuplicateLetters方法来移除字符串"bcabc"中的重复字符,并将结果打印到控制台上。
阅读全文