Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input:"bcabc"
Output:"abc"
Example 2:
Input:"cbacdcbc"
Output:"acdb"
题解如下:
class Solution {
public String removeDuplicateLetters(String s) {
if(s == null || s.length() <= 0) {
return "";
}
char[] arr = s.toCharArray();
int[] cnt = new int[26];//用于记录每个字母出现的次数
for(char c:arr) {
cnt[c-'a']++;
}
int pos = 0;
for(int i = 0;i < arr.length;i++) {
if(arr[i] < arr[pos])
pos = i;
if(--cnt[arr[i]-'a'] == 0) {
break;
}
}
return arr[pos] + removeDuplicateLetters(s.substring(pos+1).replaceAll(arr[pos]+"",""));
}
}