September 28, 2019

763. Partition Labels

763. Partition Labels

用 hashtable 存字母在 string 中出现的最后位置 Time = O(n), Space = O(n)

class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Integer> res = new ArrayList<>();
        int[] map = new int[26];
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            map[c - 'a'] = i;
        }
        int start = 0;
        int end = 0;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            end = Math.max(end, map[c - 'a']);
            if (i == end) {
                res.add(end - start + 1);
                start = end + 1;
            }
        }
        return res;
    }
}
comments powered by Disqus