Partition Labels in C++


Suppose we have a string S of lowercase letters is given. We will partition this string into as many parts as possible so that each letter appears in at most one part, finally return a list of integers representing the size of these parts. So if the string is like “ababcbacadefegdehijhklij”, output is [9,7,8], because the partitions are “ababcbaca”, “defegde”, “hijhklij”. So this is a partition so that each letter occurs in at most one part. A partition like "ababcbacadefegde", "hijhklij" is not correct, because it splits S into less parts.

To solve this, we will follow these steps −

  • define one map called cnt
  • for i in range 0 to s, cnt[s[i]] := i
  • j := 0, start := 0 and i := 0 and n := size of s
  • define one array ans
  • while i < n
    • j := max of j and cnt[s[i]]
    • if i = j, then insert i – start + 1 into ans and start := i + 1
    • increase i by 1
  • return ans

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> partitionLabels(string s) {
      map <char, int> cnt;
      for(int i = 0; i < s.size(); i++)cnt[s[i]] = i;
      int j = 0, start = 0;
      int i = 0;
      int n = s.size();
      vector <int> ans;
      while(i < n){
         j = max(j, cnt[s[i]]);
         if( i == j){
            ans.push_back(i-start+ 1);
            start = i + 1;
         }
         i++;
      }
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.partitionLabels("ababcbacadefegdehijhklij"));
}

Input

"ababcbacadefegdehijhklij"

Output

[9,7,8]

Updated on: 29-Apr-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements