LeetCode 763. Partition Labels(划分字母区间)

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1:

输入: S = "ababcbacadefegdehijhklij"
输出: [9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
   public List<Integer> partitionLabels(String S) {
        int[] last = new int[26];

        //存每个字符最后出现的下标
        //通过相同的字符作为下标来覆盖,从而得到最后一个字符的位置
        for (int i = 0; i < S.length(); i ++)
            last[S.charAt(i) - 'a'] = i;
        
        //片段区间的首尾下标
        int start = 0, end = 0;
        List<Integer> ans = new ArrayList();

        for (int i = 0; i < S.length(); i ++) {
            //拓展当前区间
            end = Math.max(end, last[S.charAt(i) - 'a']);
            //到达此区间末尾,开一个新的区间
            if (i == end) {
                ans.add(end - start + 1);
                start = end + 1;
            }
        }
        return ans;
    }
发布了581 篇原创文章 · 获赞 97 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/104902509