1. 程式人生 > >[LeetCode] Partition Labels

[LeetCode] Partition Labels

tin vector pub 含義 map list return 開始 art

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.

盡可能多的找出分區,要求每個分區中的每個字母出現次數最多。

通過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

[LeetCode] Partition Labels