763. 划分字母区间

贪心

import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<Integer> partitionLabels(String s) {

        /**
         * 用哈希表记录每个字母出现的最后位置
         */
        int[] lastIndex = new int[26];

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

        int end = 0;
        int index = 0;
        LinkedList<Integer> list = new LinkedList<>();

        /**
         * 遍历字符串,实时更新当前遇到的所有字母中的最大最后位置
         * 如果i == end,说明i之前的所有字母都已经遍历完了,也就可以分割了
         */
        for (int i = 0; i < s.length(); i++) {

            end = Math.max(end, lastIndex[s.charAt(i) - 'a']);

            if (i == end){

                list.add(i - index + 1);
                index = i + 1;
            }
        }

        return list;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

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

posted @ 2022-02-26 17:17  振袖秋枫问红叶  阅读(48)  评论(0)    收藏  举报