-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |