304 North Cardinal St.
Dorchester Center, MA 02124

# Optimal Partition of String LeetCode Solution

## Problem – Optimal Partition of String LeetCode Solution

Given a string `s`, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.

Return the minimum number of substrings in such a partition.

Note that each character should belong to exactly one substring in a partition.

Example 1:

``````Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
``````

Example 2:

``````Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
``````

Constraints:

• `1 <= s.length <= 105`
• `s` consists of only English lowercase letters.

## Optimal Partition of String LeetCode Solution in C++

``````class Solution {
public:
bool checkBit(int &flag, int &n){
return flag & (1<<n);
}
void setBit(int &flag, int &n){
flag = flag | (1<<n);
}
int partitionString(string s) {
int flag = 0;
int i = 0, ans = 1;
while(i < s.size()){
int n = s[i] - 'a';
if( checkBit(flag, n) ) {
flag = 0;
ans++;
}
setBit(flag, n);
i++;
}
return ans;
}
};
``````

## Optimal Partition of String LeetCode Solution in Java

``````class Solution {
public int partitionString(String s) {
int ans = 1;
HashSet<Character> st = new HashSet<>();
for(int i=0;i<s.length();i++){
// Insert Till we find duplicate element.
if(!st.contains(s.charAt(i))){
}
else{
// If we found duplicate char then increment count and clear set and start with new set.
ans++;
st.clear();
}
}
return ans;
}
}
``````

## Optimal Partition of String LeetCode Solution in Python

``````class Solution:
def partitionString(self, s: str) -> int:

def isUnique(s):
return len(set(s)) == len(s)

left = 0
res = 0
for right in range(1,len(s)+1):
if not isUnique(s[left:right]):
res += 1
left = right-1

return res+1 # don't forget there is still one partition we didn't add into res
``````
##### Optimal Partition of String LeetCode Solution Review:

In our experience, we suggest you solve this Optimal Partition of String LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Optimal Partition of String LeetCode Solution

Find on Leetcode

##### Conclusion:

I hope this Optimal Partition of String LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions