leetcode 763. Partition Labels | 763. 划分字母区间(双指针)

x33g5p2x  于2021-12-01 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(242)

题目

https://leetcode.com/problems/partition-labels/

题解

将问题转化成线段分割问题:找到所有可以切的点,使得每一个线段都不会被切到

class Solution {
    public List<Integer> partitionLabels(String s) {
        int[][] range = new int[26][2];
        for (int i = 0; i < 26; i++) {
            range[i][0] = -1;
            range[i][1] = -1;
        }

        for (int i = 0; i < s.length(); i++) {
            int p = s.charAt(i) - 'a';
            if (range[p][0] == -1) range[p][0] = i;
            range[p][1] = i;
        }

        Arrays.sort(range, (o1, o2) -> {
            if (o1[0] == o2[0]) return o1[1] - o2[1];
            else return o1[0] - o2[0];
        });
        
        List<Integer> result = new ArrayList<>();
        int start = -1;
        int end = -1;
        for (int[] r : range) {
            if (r[0] == -1) {
                continue;
            } else if (start == -1) {
                start = r[0];
                end = r[1];
            } else {
                if (r[0] > start && r[0] < end) {
                    end = Math.max(end, r[1]);
                } else {
                    result.add(end - start + 1);
                    start = r[0];
                    end = r[1];
                }
            }
        }
        result.add(end - start + 1);
        return result;
    }
}

相关文章