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:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Solution: reference
After determining the greedy choice s[i], we get a new string s' from s by
- removing all letters to the left of s[i],
- removing all s[i]'s from s.
public String removeDuplicateLetters(String s) {
int[] count = new int[26];
int pos = 0;
for(int i=0; i<s.length(); i++) count[s.charAt(i) - 'a']++;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i)< s.charAt(pos)) pos = i;
if(--count[s.charAt(i) - 'a'] == 0) break;
}
return s.length() == 0? "" : s.charAt(pos) + removeDuplicateLetters(s.substring(pos+1).replaceAll(""+ s.charAt(pos), ""));
}

本文介绍了一种算法,用于从仅包含小写字母的字符串中移除所有重复的字符,确保每个字母只出现一次,并保持结果字符串在字典序上尽可能最小。通过一个递归函数实现该算法。
1681

被折叠的 条评论
为什么被折叠?



