3223 - Minimum Length of String After Operations
You are given a string s.
You can perform the following process on s any number of times:
- Choose an index
iin the string such that there is at least one character to the left of indexithat is equal tos[i], and at least one character to the right that is also equal tos[i]. - Delete the closest character to the left of index
ithat is equal tos[i]. - Delete the closest character to the right of index
ithat is equal tos[i].
Return the minimum length of the final string s that you can achieve.
Example 1:
Input: s = "abaacbcbb"
Output: 5
Explanation:
We do the following operations:
- Choose index 2, then remove the characters at indices 0 and 3. The resulting string is
s = "bacbcbb". - Choose index 3, then remove the characters at indices 0 and 5. The resulting string is
s = "acbcb".
Example 2:
Input: s = "aa"
Output: 2
Explanation:
We cannot perform any operations, so we return the length of the original string.
Constraints:
1 <= s.length <= 2 * 105sconsists only of lowercase English letters.
Solution 1: Counting
C++
class Solution { public: int minimumLength(string s) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } int ans = 0; for (int x : cnt) { if (x) { ans += x % 2 ? 1 : 2; } } return ans; } };
JAVA
class Solution { public int minimumLength(String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } int ans = 0; for (int x : cnt) { if (x > 0) { ans += x % 2 == 1 ? 1 : 2; } } return ans; } }
PYTHON
class Solution: def minimumLength(self, s: str) -> int: cnt = [0] * 26 for c in s: cnt[ord(c) - ord('a')] += 1 ans = 0 for x in cnt: if x: ans += 1 if x % 2 else 2 return ans
Comments
Post a Comment