3223. Minimum Length of String After Operations #1136
-
Topics: You are given a string You can perform the following process on
Return the minimum length of the final string Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to focus on the frequency of each character in the string. Here’s the approach to solve it: Approach:
Let's implement this solution in PHP: 3223. Minimum Length of String After Operations <?php
/**
* @param String $s
* @return Integer
*/
function minimumLength($s) {
// Step 1: Count the frequency of each character
$frequency = array();
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
$char = $s[$i];
if (!isset($frequency[$char])) {
$frequency[$char] = 0;
}
$frequency[$char]++;
}
// Step 2: Reduce frequency of characters with count >= 3
foreach ($frequency as $char => $count) {
if ($count >= 3) {
// Remove pairs of characters
$frequency[$char] = $count % 2 == 0 ? 2 : 1;
}
}
// Step 3: Calculate the minimum length
$minLength = 0;
foreach ($frequency as $count) {
$minLength += $count;
}
return $minLength;
}
// Example 1
$s1 = "abaacbcbb";
echo "Input: $s1\n";
echo "Output: " . minimumLength($s1) . "\n";
// Example 2
$s2 = "aa";
echo "Input: $s2\n";
echo "Output: " . minimumLength($s2) . "\n";
?> Explanation:
Example Walkthrough:Example 1:
Example 2:
Complexity:
This solution is efficient and works well within the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We need to focus on the frequency of each character in the string. Here’s the approach to solve it:
Approach:
Count Character Frequencies:
Reduce Characters with Frequency >= 3:
Calculate the Minimum Length:
Let's implement this solution in PHP: 3223. Minimum Length of String After Operations