leetcode 763 .Partition Labels 题解

Posted J1ac

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

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

 

【思路】这道题要我们把字符串划分成几个每个元素最多只在一个部分存在的几部分,看到这种题目就知道是和每个字母在字符串中出现的位置密密相关。

一个字母只能在一个区间出现说明这个字母的最后出现控制着这个字母的区间,我们对每个字母都求出出现的最后面的坐标,然后从左向右扫描,取到每个字母出现的最右位置并保存最大值,一个区间的结束必定意味着最后的字母的右边界恰好是前面所有字母的最大右边界,于是就能找到这个区间,具体做法见代码:

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> res;
        int ss = S.size();
        vector<int> d(128,0);
        for(int i = 0; i<ss; ++i){ //建立最右坐标的标志,这里只有字母,所以用vector应该比unordered_map快
            d[S[i]] = i;
        }
        int start = 0;//当前区间起始点
        int range = -1;//当前区间所需最右边界
        for(int i = 0; i<ss; ++i){
            range = max(range, d[S[i]]);//每个字母更新所需的右边界
            if(range == i){//当右边界到达的时候截取并保存
                res.push_back(i+1-start);
                start = i + 1;//更新区间起点
            }
        }
        return res;
    }
};

 

以上是关于leetcode 763 .Partition Labels 题解的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 763. Partition Labels

leetcode 763 .Partition Labels 题解

Leetcode 763. Partition Labels

leetcode 763. Partition Labels 划分字母区间(中等)

763. Partition Labels

763. Partition Labels(贪心)