2716. Minimize String Length
Description
Given a string s, you have two types of operation:
- Choose an index
iin the string, and letcbe the character in positioni. Delete the closest occurrence ofcto the left ofi(if exists). - Choose an index
iin the string, and letcbe the character in positioni. Delete the closest occurrence ofcto the right ofi(if exists).
Your task is to minimize the length of s by performing the above operations zero or more times.
Return an integer denoting the length of the minimized string.
Example 1:
Input: s = "aaabc"
Output: 3
Explanation:
- Operation 2: we choose
i = 1socis 'a', then we removes[2]as it is closest 'a' character to the right ofs[1].
sbecomes "aabc" after this. - Operation 1: we choose
i = 1socis 'a', then we removes[0]as it is closest 'a' character to the left ofs[1].
sbecomes "abc" after this.
Example 2:
Input: s = "cbbd"
Output: 3
Explanation:
- Operation 1: we choose
i = 2socis 'b', then we removes[1]as it is closest 'b' character to the left ofs[1].
sbecomes "cbd" after this.
Example 3:
Input: s = "baadccab"
Output: 4
Explanation:
- Operation 1: we choose
i = 6socis 'a', then we removes[2]as it is closest 'a' character to the left ofs[6].
sbecomes "badccab" after this. - Operation 2: we choose
i = 0socis 'b', then we removes[6]as it is closest 'b' character to the right ofs[0].
sbecomes "badcca" fter this. - Operation 2: we choose
i = 3socis 'c', then we removes[4]as it is closest 'c' character to the right ofs[3].
sbecomes "badca" after this. - Operation 1: we choose
i = 4socis 'a', then we removes[1]as it is closest 'a' character to the left ofs[4].
sbecomes "bdca" after this.
Constraints:
1 <= s.length <= 100scontains only lowercase English letters
Solutions
Solution 1: Hash Table
The problem can actually be transformed into finding the number of distinct characters in the string. Therefore, we only need to count the number of distinct characters in the string.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\). The space complexity is \(O(|\Sigma|)\), where \(\Sigma\) is the character set. In this case, it's lowercase English letters, so \(|\Sigma|=26\).
1 2 3 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 | |
1 2 3 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 | |