LeetCode题解系列--763. 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.
Note:

S will have length in range [1, 500].
S will consist of lowercase letters (‘a’ to ‘z’) only.

题意梗概

这题的意思是将一个字符串划分成尽可能多的字串,使得对于任意字符(a、b。。等)只会出现在一个字串中

思路

使用贪心算法
题目要求是“尽可能多”的子串,换句话说就是每个字串“尽可能短”。
那么在满足题目要求的条件下,每个字串应该包含尽可能少的字符种类,首先我们确定一个子串的开始点(这必定是存在的,因为第一个字串肯定是从0开始,而第二个是第一个结尾后开始),从这个开始点向后遍历,这个子串的结束点就是便利过程中遇到的字符最后出现的下标值中最大的。说起来很绕口,其实用代码表示很简单。

解答

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> result;
        vector<int> lastAppear(26, -1);
        int length = S.size();
        // find each character appear last
        for (int i = length - 1; i > -1; --i) {
            lastAppear[S[i] - 'a'] = max(i, lastAppear[S[i] - 'a']);
        }
        // greedy goes here
        int start = 0;
        int end = lastAppear[S[0] - 'a'];
        int curCharLastAppear = 0;
        for (int i = 0; i < length; ++i) {
            curCharLastAppear = lastAppear[S[i] - 'a'];
            end = max(end, curCharLastAppear);
            if (i == end) {
                // find a partition
                result.push_back(end - start + 1);
                start = end + 1;
            }
        }
        return result;
    }
};

你可能感兴趣的:(C++,leetcode)