天天看點

763. Partition Labels方法1: two pointers + greedy

763. Partition Labels

  • 方法1: two pointers + greedy
    • Complexity

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.

方法1: two pointers + greedy

grandyang:https://www.cnblogs.com/grandyang/p/8654822.html

思路:

題意要求把string拆成盡可能多的字串,但是同一個字母不能在超過一個字串中出現。那麼在周遊的過程中想要知道一個位置是否能斷,需要明确此時所有出現過的字母是否後面不會再出現。換句話說,我們要提前知道每一個字母出現的最後一個位置。是以周遊第一遍來掃出所有字母最後出現在的位置。當第二次周遊時,首先我們記錄一個last來對應proposed終點。我們周遊到的每個字母,都有可能要求extend目前proposed終點,i.e. 一個字母出現,它的last必須被包含在目前字串内,直到i == last,此時可以明确所有出現的字母last position都在此之前,可以截斷在i,推入一個結果,移動左指針标記的start到i + 1。

Complexity

Time complexity: O(n)

Space complexity: O(1)

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> result;
        unordered_map<char, int> hash;
        int start = 0, last = 0;
        for (int i = 0; i < S.size(); i++) hash[S[i]] = i;
        for (int i = 0; i < S.size(); i++) {
            last = max(last, hash[S[i]]);
            if (i == last) {
                result.push_back(i - start + 1);
                start = i + 1;
            }
        }
        return result;
    }
};