Santosh yadav
Sep 11, 2022

--

LeetCode 2405. Optimal Partition of String in JavaScript

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.

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.
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").

Solution

/**
* @param {string} s
* @return {number}
*/
var partitionString = function(s) {//3
//abacaba //a
if(s.length==1)
return 1;
if(s.length==0)
return 0;
let res=1;
let map=new Map();
for(let char of s){
if(!map.get(char))
map.set(char,1)
else{
map.clear();
map.set(char,1)
res++;
}

}
return res;
};

--

--

Santosh yadav

Santosh Yadav is a Lead Frontend Engineer having interest in problem solving, data structures and algorithms.