-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3498 from realsubodh/main
Create: 2405-optimal-partition-of-string.cpp
- Loading branch information
Showing
1 changed file
with
28 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,28 @@ | ||
class Solution { | ||
public: | ||
int minPartitions(std::string s) { | ||
// Set to keep track of characters in the current substring | ||
std::unordered_set<char> currentChars; | ||
// Variable to count the number of partitions | ||
int partitionCount = 0; | ||
|
||
// Iterate over each character in the string | ||
for (char c : s) { | ||
// If the character is already in the set, it means we've encountered a duplicate | ||
if (currentChars.find(c) != currentChars.end()) { | ||
// Increment the partition count and start a new substring | ||
partitionCount++; | ||
currentChars.clear(); | ||
} | ||
// Add the current character to the set | ||
currentChars.insert(c); | ||
} | ||
|
||
// There will be at least one partition at the end if currentChars is not empty | ||
if (!currentChars.empty()) { | ||
partitionCount++; | ||
} | ||
|
||
return partitionCount; | ||
} | ||
}; |