天天看點

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