1. 程式人生 > >763. Partition Labels

763. Partition Labels

題目 ade == bsp range labels size nsis split

題目描述:

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.

解題思路:

遍歷S,找到S[i]在S中最後出現的位置j,此時遍歷i到j中的每個元素S[index],若S[index]在S中最後出現的位置大於j時,j等於S[index]在S中最後出現的位置,當index等於j時結束內循環。

預先記錄每個字母在S最後出現的位置可以提高運算時間。

代碼:

 1 class Solution {
 2 public:
 3     vector<int> partitionLabels(string
S) { 4 vector<int> res; 5 for (int i = 0; i < S.size();) { 6 size_t j = S.find_last_of(S[i]); 7 if (i == j) { 8 res.push_back(1); 9 i += 1; 10 continue; 11 } 12 for (int index = i + 1
; index <= j; ++index) { 13 size_t tmp = S.find_last_of(S[index]); 14 if (tmp > j) 15 j = tmp; 16 } 17 res.push_back(j-i+1); 18 i = j + 1; 19 } 20 return res; 21 } 22 };

763. Partition Labels