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.
尽可能多的找出分区,要求每个分区中的每个字母出现次数最多。
通过Example可以大致了解题目含义。
贪心算法思路:
1、使用一个map来存储每个字母出现的最大索引值。
如例子所示:
a-8, b-5, c-7, d-14, e-15, f-11, g-13, h-19, i-22, j-23, k-20, l-21
2、遍历数组,要求在当前字母所包含的分区最大。
如ababcbaca.
由map可知,a-8,在索引0-8之间所有字母在map中的最大索引不超过8。所以可以构成一个分区
这时从索引9开始遍历。d-14,在所有9-14之间的字母中,存在e的最大索引超过了14,所以令分区扩大为9-15。
剩下的部分按照这个思路遍历即可。
3、将各分区的大小放去res数组中即可。
class Solution { public: vector<int> partitionLabels(string S) { vector<int> res; unordered_map<char, int> max_pos; for (int i = 0; i < S.size(); i++) { max_pos[S[i]] = i; } for (int i = 0; i < S.size();) { int beg = i; int end = max_pos[S[i]]; for (int j = i + 1; j < end; j++) { end = max(end, max_pos[S[j]]); } res.push_back(end - beg + 1); i = end + 1; } return res; } }; // 10 ms