LeetCode 763. Partition Labels

title:

date: 2022-06-28 16:23:00

tags:

categories: LeetCode

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

题目

链接

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

问题描述

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

示例

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

提示

S的长度在[1, 500]之间。
S只包含小写字母 'a' 到 'z' 。

思路

首先先遍历一遍,找到每个字母最后出现的位置,之后从开头开始拓展,随时更新字符串中存在的字符的最远位置,为tag,之后,当tag == i的时候,就代表这里可以形成一个最短的符合条件的片段,更新。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(c)

代码

Java

    public List<Integer> partitionLabels(String s) {
        List<Integer> ans = new ArrayList<>();
        int[] word = new int[26];

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            word[c - 'a'] = i;
        }
        int tag = 0;
        int index = -1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            tag = Math.max(word[c - 'a'], tag);
            if (i == tag) {
                ans.add(i - index);
                index = i;
            }
        }
        return ans;
    }
posted @ 2022-06-28 16:35  cheng102e  阅读(21)  评论(0编辑  收藏  举报