天天看點

貪心算法leetcode-763

int[] lastShow = new int[26];
        var list = new LinkedList<Integer>();
        for (int i = 0; i < s.length(); i++) {
            lastShow[s.charAt(i) - 'a'] = i;
        }

        int end = lastShow[s.charAt(0) - 'a'];
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i == end) {
                list.add(++count);
                count = 0;
                if (i+1 < s.length()) end = lastShow[s.charAt(i+1) - 'a'];//end = -1;
                continue;
            }
            if (lastShow[s.charAt(i) - 'a'] > end) end = lastShow[s.charAt(i) - 'a'];
            count++;
        }
        if (count != 0) list.add(count);
        return list;      

首先,建立一個含有26個位置的數組,放的是字元串中每一個字母最後出現的下标。比如說, lastshow[0]放的就是‘a’最後出現的下标, lastshow[3]放的就是‘d’最後出現的下标。

然後周遊字元串,如果目前位置等于現在貪心的“最近最後一個”的地方,就可以把它們做一個小數組了。如果目前位置的字母最後出現位置大于目前的“最近最後一個”的下标,就更新這個值。