LeetCode刷题实战316:去除重复字母
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.
示例
示例 1:
输入:s = "bcabc"
输出:"abc"
示例 2:
输入:s = "cbacdcbc"
输出:"acdb"
解题
public class RemoveDuplicateLetters {
public static String removeDuplicateLetters(String s){
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c=s.charAt(i);
if(stack.contains(c))
continue;
while(!stack.isEmpty() && stack.peek()>c && s.indexOf(stack.peek(),i)!=-1)
stack.pop();
stack.push(c);
}
char chars[]=new char[stack.size()];
for (int i = 0; i < stack.size(); i++) {
chars[i]=stack.get(i);
}
return new String(chars);
}
public static void main(String[] args) {
String string = "bbcaac";
System.out.println(removeDuplicateLetters(string));
}
}