LeetCode题解系列--763. Partition Labels
2018-01-18 12:24
666 查看
描述
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; } };
相关文章推荐
- LeetCode题解系列--122. Best Time to Buy and Sell Stock II
- LeetCode题解系列--5. Longest Palindromic Substring
- Leetcode 题解系列(四)
- LeetCode题解系列--188. Best Time to Buy and Sell Stock IV
- LeetCode题解系列--215. Kth Largest Element in an Array
- Leetcode 题解系列(二)
- Leetcode 题解系列(十)
- Leetcode 题解系列(十六)
- Leetcode 题解系列(十一)
- Leetcode 题解系列(十二)
- Leetcode 题解系列(六)
- Leetcode 题解系列(一)
- Leetcode 题解系列(七)
- LeetCode题解系列--712. Minimum ASCII Delete Sum for Two Strings
- Leetcode 题解系列(十七)
- Leetcode 题解系列(三)
- LeetCode题解系列--4. Median of Two Sorted Arrays
- LeetCode题解系列--123. Best Time to Buy and Sell Stock III
- LeetCode题解系列--684. Redundant Connection
- Leetcode 题解系列(十四)