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

LC 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.

Runtime: 8 ms, faster than 43.40% of C++ online submissions for Partition Labels.

第一次實現用的是map,第二次實現用的是陣列,差了一倍的執行速度。

#include <vector>
#include 
<string> #include <unordered_map> #include <map> #include <iostream> using namespace std; class Solution { public: vector<int> partitionLabels(string S) { int map[256]; for(int i=0; i<S.size(); i++){ map[(int)S[i]] = i; } int idx = 0; vector
<int> ret; while(idx < S.size()){ int tmpidx = idx; int maxback = map[(int)S[tmpidx]]+1; while(tmpidx < S.size() && tmpidx < maxback){ maxback = max(maxback, map[(int)S[tmpidx]]+1); tmpidx++; } ret.push_back(maxback - idx); idx = maxback; } return ret; } };