763. Partition Labels

题目描述:

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 };
原文地址:https://www.cnblogs.com/gsz-/p/9409856.html