763. Partition Labels

2018/07/01 leetcode 共 1224 字,约 4 分钟

title

problem link

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.

solution

分隔字符串使同种字符出现在一起, 贪心算法

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

下面等价

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

Search

    Table of Contents