3174. Clear Digits #1295
-
Topics: You are given a string Your task is to remove all digits by doing this operation repeatedly:
Return the resulting string after removing all digits. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to remove all digits from a string by repeatedly deleting each digit and the closest non-digit character to its left. The goal is to efficiently simulate this process and return the resulting string after all deletions. ApproachThe key insight is to use a stack to keep track of non-digit characters as we process the string from left to right. When we encounter a digit, we remove the closest non-digit character to its left, which is the top element of the stack. This approach ensures that we efficiently track and remove the necessary characters in a single pass through the string.
Let's implement this solution in PHP: 3174. Clear Digits <?php
/**
* @param String $s
* @return String
*/
function clearDigits($s) {
$stack = array();
foreach (str_split($s) as $char) {
if (ctype_digit($char)) {
if (!empty($stack)) {
array_pop($stack);
}
} else {
array_push($stack, $char);
}
}
return implode('', $stack);
}
// Example usage:
$s1 = "abc";
$s2 = "cb34";
echo clearDigits($s1) . "\n"; // Output: "abc"
echo clearDigits($s2) . "\n"; // Output: ""
?> Explanation:
This method efficiently simulates the required deletions using a stack, ensuring that we handle each character in a single pass and maintain optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to remove all digits from a string by repeatedly deleting each digit and the closest non-digit character to its left. The goal is to efficiently simulate this process and return the resulting string after all deletions.
Approach
The key insight is to use a stack to keep track of non-digit characters as we process the string from left to right. When we encounter a digit, we remove the closest non-digit character to its left, which is the top element of the stack. This approach ensures that we efficiently track and remove the necessary characters in a single pass through the string.