316. Remove Duplicate Letters
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public String removeDuplicateLetters(String s) {
if(s == null || s.length() == 0) return "";
int[] count = new int[128];
char[] result = new char[26];
boolean[] assigned = new boolean[128];
int sLen = s.length();
for(int i = 0; i < sLen; i++) {
count[s.charAt(i)]++;
}
char ch;
int end = -1;
for(int i = 0; i < sLen; i++) {
ch = s.charAt(i);
count[ch]--;
if(assigned[ch]) continue;
while(end >= 0 && result[end] > ch && count[result[end]] > 0) {
assigned[result[end]] = false;
end--;
}
end++;
result[end] = ch;
assigned[ch] = true;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i <= end; i++) {
sb.append(result[i]);
}
return sb.toString();
}
}