1957. Delete Characters to Make Fancy String #775
-
Topics: A fancy string is a string where no three consecutive characters are equal. Given a string Return the final string after the deletion. It can be shown that the answer will always be unique. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to ensure that no three consecutive characters are the same in the final string. We'll iterate through the input string and build a new "fancy" string by keeping track of the previous two characters. If a third consecutive character matches the last two, we skip it. Otherwise, we add it to the output. Let's implement this solution in PHP: 1957. Delete Characters to Make Fancy String <?php
/**
* @param String $s
* @return String
*/
function makeFancyString($s) {
$result = "";
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
// Check if last two characters in the result are the same as current character
if ($i > 1 && $s[$i] == $result[strlen($result) - 1] && $s[$i] == $result[strlen($result) - 2]) {
continue; // Skip adding the character if it makes three consecutive
}
$result .= $s[$i]; // Add character to result
}
return $result;
}
// Example usage:
echo makeFancyString("leeetcode"); // Output: "leetcode"
echo "\n";
echo makeFancyString("aaabaaaa"); // Output: "aabaa"
echo "\n";
echo makeFancyString("aab"); // Output: "aab"
?> Explanation:
Complexity Analysis
This solution meets the constraints efficiently and ensures that the final string has no three consecutive identical characters. |
Beta Was this translation helpful? Give feedback.
We need to ensure that no three consecutive characters are the same in the final string. We'll iterate through the input string and build a new "fancy" string by keeping track of the previous two characters. If a third consecutive character matches the last two, we skip it. Otherwise, we add it to the output.
Let's implement this solution in PHP: 1957. Delete Characters to Make Fancy String