Skip to content

Commit

Permalink
optimal-partition-of-string
Browse files Browse the repository at this point in the history
  • Loading branch information
aolenevme authored Apr 5, 2023
1 parent f24df5e commit b876a0b
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions string/optimal-partition-of-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
2405. Optimal Partition of String
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.
*/

/**
* @param {string} s
* @return {number}
*/
var partitionString = function (s) {
let set = new Set();
let counter = 0;

for (const char of s) {
if (set.has(char)) {
counter++;

set.clear();
}

set.add(char);
}

if (set.size > 0) {
counter++;
}

return counter;
};

0 comments on commit b876a0b

Please sign in to comment.