天天看点

763. Partition Labels763. Partition Labels#

763. Partition Labels#

1. 题目描述

题目链接

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:

Input: S = “ababcbacadefegdehijhklij”

Output: [9,7,8]

Explanation:

The partition is “ababcbaca”, “defegde”, “hijhklij”.

This is a partition so that each letter appears in at most one part.

A partition like “ababcbacadefegde”, “hijhklij” is incorrect, because it splits S into less parts.

Note:

S will have length in range [1, 500].

S will consist of lowercase letters (‘a’ to ‘z’) only.

2. 题目分析

这题意比较难理解,刚开始读了好几遍,都没看懂。意思就是说,将一个长字符串S,进行分割多个子串,分割时必须保证每个字符只能出现在一个子串中,并且子串必须是最小子串,就是不能继续分割了。如"ababcbacadefegde",就还能分割: “ababcbaca”, “defegde”,所以"ababcbacadefegde"不是最小子串。

开始时,这里有个让我疑惑的地方是,像这种"ababcbacadefegdehijhklijxwz",前面部分分割成"ababcbaca", “defegde”, “hijhklij”,但"xwz"是作为一个整体呢,还是继续分割成"x",“w”,"z"呢?后面经过测试,是后者。仔细想想按题目的意思,"xwz"是需要继续分割的,“x”,“w”,"z"才是最小子串。

3. 解决思路

首先遍历整个字符串S,记录每个字符最后出现的下标到一个maxIndex数组中。

然后,遍历字符串的时候,对于字符串S而言,从S最左边的第一个字母,然后从数组maxIndex中找到该字母在S中最右边出现的位置,这里假设为end,如果从S最左边到end之间有一个字母最右边的索引在end右边,那么更新end,继续遍历,直到S最左端到i的字母已经全部遍历了一遍,这个时候0~end就是一个最小的分组,将S切分,对end+1到S最右端继续以上操作,重复执行该操作直到S切分完毕

4. 代码实现(java)

public List<Integer> partitionLabels(String S) {
        List<Integer> list = new LinkedList<>();
        if(S == null || S.isEmpty()){
            return list;
        }
        int len = S.length();
        int[] maxIndex = new int[26];
        for(int i = 0; i < len; i++) {
            maxIndex[S.charAt(i) - 'a'] = i;
        }

        int start = 0;
        int end = start;
        int i;
        int partitionLen = 0;
        while(end < len){
            i = start;

            while(i <= end && end < len){
                end = Math.max(end, maxIndex[S.charAt(i) - 'a']);
                i++;
            }
            partitionLen = end - start + 1;
            list.add(partitionLen);
            start = end + 1;
            end = start;
        }
        return list;
    }