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;
  }
};

猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10188343.html
今日推荐