Given a string
Return the minimum number of substrings in such a partition.
Output: 4
Explanation: Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
So, we can return 4.
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.
Contents
Solution 1 - Check contiguous unique substring using a HashSet
In this approach, we will use a
Implementation steps:
-
Create a
HashSet to track unique characters, call itset , and an integerresult for the result, initialize this with 1 (see note below, why we are initializing it with 1). -
Then, loop through the characters of input string
s , check if theset already contains the current character or not, if it contains, that means all the characters added until now will form a unique substring. So, increment theresult and clear theset for next subsubstring starting from current character, add then add current character to theset . -
Finally return the
result .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1), though we are using a
Above implementations source code can be found at