天天看点

LeetCode763. Partition Labels

题目描述:

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.
           

找到字符串的一种分割方式,即分割后的多个字符串之间不能存在相同的字符,要求:找到能够分到最多字符串的方式。

解题思路: 

本题是一个贪心问题,当前字符与最后一次出现这个字符之间的字符串一定是被分割到一个子字符串中的。因此需要维护一个当前子字符串中的字符出现的最大索引,不断更新这个最大索引,当指针i走到最大索引的后边的时候,说明指针前面的字符串可以被分成一个子字符串了。

Python代码:

class Solution:
    def partitionLabels(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        max_index = {c: i for i, c in enumerate(S)}
        max_tem, tem = 0, 0
        res = []
        for i in range(len(S)):
            if max_index[S[i]] > max_tem:
                max_tem = max_index[S[i]]
            if i >= max_tem:
                res.append(i - tem + 1)
                tem = i + 1
        return res
           

Java代码:

class Solution {
    public List<Integer> partitionLabels(String S) {
        int ls = S.length();
        int maxTem = 0, tem = 0;
        ArrayList res = new ArrayList();
        int lastIndex[] = new int[ls];
        for (int i = 0; i < ls; i++) {
            lastIndex[i] = S.lastIndexOf(S.charAt(i));
            // System.out.println(last_index[i]);
        }
        for (int i = 0; i < ls; i++) {
            if (lastIndex[i] > maxTem) {
                maxTem = lastIndex[i];
            }
            if (i >= maxTem) {
                res.add(i - tem + 1);
                tem = i + 1;
                maxTem = 0;
            }
        }
        return res;
    }
}
           
LeetCode763. Partition Labels
LeetCode763. Partition Labels