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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值