1. 程式人生 > >LeetCode | 763. Partition Labels 中等偏難貪心演算法 把一個字串劃分為有獨立字母的最多組的劃分方法

LeetCode | 763. Partition Labels 中等偏難貪心演算法 把一個字串劃分為有獨立字母的最多組的劃分方法

AstringSof lowercase letters is given. We want to partition thisstring into as many parts as possible so that each letter appears in at mostone part, and return a list of integers representing the size of these parts.

Example1:

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 mostone part.

A partition like "ababcbacadefegde","hijhklij" is incorrect, because it splits S into less parts.

Note:

1.      Swill have length in range[1, 500].

2.      Swill consist of lowercase letters ('a'to'z') only.

從這一題開始有些難度了,這題要求你把一個字串劃分為儘可能多的片段,每個片段儘可能包含多的字母

這一題我是使用貪心演算法的思想解決的,對於字串S而言,其最左邊的一組一定包含S最左邊的第一個字母,然後檢索該字母在S中最右邊的位置,這裡假設為i,如果從S最左邊到i之間有一個字母最右邊的索引在i右邊,那麼更新i,繼續遍歷,直到S最左端到i的字母已經全部遍歷了一遍,這個時候0~i就是一個最小的分組,將S切分,對i+1到S最右端繼續以上操作

執行該操作直到S切分完畢

class Solution {
public:
  int divide(string S, int start, int end,int letterRight[26])
{
	int left, right;
	left = start;
	right = letterRight[S[left] - 'a'];
	for (int i = left+1; i <= right; i++)
	{
		if (letterRight[S[i]-'a'] > right) right = letterRight[S[i] - 'a'];
	}
	return right - left+1;

}

vector<int> partitionLabels(string S) {
	int letterRight[26];
	vector<int> result;

	for (int i = 0; i < 26; i++)
	{
		int t = S.find_last_of((char)( i + 'a'));
		letterRight[i] = t;
	}
	int start = 0; int end = S.size(); int tmp;
	while (start < end)
	{
		tmp = divide(S, start, end, letterRight);
		result.push_back(tmp);
		start += tmp;
	}
	return result;
}
};