当前位置:网站首页>2022.04.23(LC_763_划分字母区间)

2022.04.23(LC_763_划分字母区间)

2022-04-23 18:51:00 Leeli9316

方法:贪心

class Solution {
    public List<Integer> partitionLabels(String s) {
        //记录每个字母出现的最后位置
        int[] lastPos = new int[26];
        for (int i = 0; i < s.length(); i++) {
            lastPos[s.charAt(i) - 'a'] = i;
        }
        List<Integer> ans = new ArrayList<>();
        int start = 0; //开始位置
        int end = 0; //结束位置
        for (int i = 0; i < s.length(); i++) {
            //更新字符出现的最远位置
            end = Math.max(end, lastPos[s.charAt(i) - 'a']);
            if (i == end) {
                ans.add(end - start + 1);
                start = i + 1;
            }
        }
        return ans;
    }
}

版权声明
本文为[Leeli9316]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Leeli9316/article/details/124360610