[LeetCode]Remove Duplicate Letters

思路借鉴了https://leetcode.com/discuss/73806/15-ms-java-solution

for "cbacdcbc", we counts each letter's index:

a----2
b----1,6
c----0,3,5,7
d----4

we go from a to d, to find the first letter who has a index smaller than the largest index of the rest. Here, index 2 of letter a is smaller than 6, 7, 4, so we first pick a; then we remove all index smaller than 2, and we have:

b----6
c----3,5,7
d----4

the next round we pick c not b, why ? cuz 6 of b is larger than 4, but 3 of c is smaller than 4 and 6.

b---6
d---4

then we pick d and b to form "acbd"

 

public class Solution {
    public String removeDuplicateLetters(String s) {
        HashMap<Character, List<Integer>> map = new HashMap<Character, List<Integer>>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            List<Integer> list = map.containsKey(s.charAt(i)) ? map.get(s.charAt(i)) : new LinkedList<Integer>();
            list.add(i);
            map.put(s.charAt(i), list);
        }
        String result = "";
        while (!map.isEmpty()) {
            for (char ch1 = 'a'; ch1 <= 'z'; ch1++) {
                if(!map.containsKey(ch1)) {
                    continue;
                } else {
                    boolean flg = true;
                    int index = map.get(ch1).get(0);
                    for (char ch2 = (char) (ch1 + 1); ch2 <= 'z'; ch2++) {
                        if (map.containsKey(ch2)) {
                            List<Integer> list = map.get(ch2);
                            if (index > list.get(list.size() - 1)) {
                                flg = false;
                                break;
                            }
                        }
                    }
                    if (flg) {
                        result += ch1;
                        map.remove(ch1);
                        for (char ch2 = 'a'; ch2 <= 'z'; ch2 ++) {
                            if (map.containsKey(ch2)) {
                                List<Integer> list = map.get(ch2);
                                while (!list.isEmpty() && list.get(0) < index) {
                                    list.remove(0);
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
        return result;
    }
}

 

posted @ 2015-12-14 06:38  Weizheng_Love_Coding  阅读(280)  评论(0编辑  收藏  举报