
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 −
#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]
- Related Articles
- Partition problem
- Partition Values
- Partition List in C++
- Partition Problem in C++
- Program to partition two strings such that each partition forms anagram in Python
- Array Partition I in Python
- Equal Tree Partition in C++
- Partition Equal Subset Sum in C++
- Partition Array into Disjoint Intervals in C++
- Program to partition color list in Python
- Partition Array for Maximum Sum in Python
- Find a partition point in array in C++
- Hiding major tick labels while showing minor tick labels in Matplotlib
- Bootstrap Labels
- Partition to K Equal Sum Subsets in C++

Advertisements