316. Remove Duplicate Letters

来源:互联网 发布:淘宝怎么找代理商 编辑:程序博客网 时间:2024/06/10 19:20

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"



思路:刚开始想到的是贪心算法,但贪婪的规则貌似不好想,在Discuss找到一个循环递归的解法

关键就是在某一个字符最后出现的地方做文章,也许这就是所谓的突破点吧!


/* * 令 x = 'a'最后一次出现的位置,那么结果一定包含 在x之前(包括x)的某个字符,否则就没有'a'了(不一定就是'a') * 既然要包含一个,那肯定是最小的一个 * 如果最小的就是'a',那就从'a'后面的一个继续下去 * 如果最小的不是'a',那就从最小的那个个继续下去,因为可以断定这个最小的位置肯定在'a'之前,所以'a'后面肯定还是会包括进来的 * 因为目前最小的肯定是要包括到结果中的,那后面的即使有最小的也不能包括就去,所以递归的时候要去掉 *  * 其他的字符也是类似 */public class Solution {    public String removeDuplicateLetters(String s) {        if("".equals(s))return "";            char[] cs = s.toCharArray();        int[] cnt = new int[26];        for(char c : cs)cnt[c-'a']++;                int minPos = 0;        for(int i=0; i<cs.length; i++) {        if(cs[i] < cs[minPos])minPos = i;// 获取最小的字符index        if(--cnt[cs[i]-'a'] == 0)break;// 当某个字符是最后一次出现时,跳出循环,拿出最小的继续递归        }            return "" + cs[minPos] + removeDuplicateLetters(s.substring(minPos+1).replace(""+cs[minPos], ""));    }}


0 0
原创粉丝点击