반응형
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
Constraints:
- 1 <= k <= num.length <= 105
- num consists of only digits.
- num does not have any leading zeros except for the zero itself.
public class Solution {
public string RemoveKdigits(string num, int k) {
char[] result = new char[num.Length];
int top = 0;
foreach (char c in num){
// Remove digits from the stack as long as they are greater than current digit
// and there are still digits to remove
while(top > 0 && result[top - 1] > c && k > 0) {
top--;
k--;
}
// Add current digit to the stack
result[top++] = c;
}
// If there are still digits to remove, remove them from the end
while (k > 0 && top > 0) {
top--;
k--;
}
// Trim leading zeros
int start = 0;
while (start < top && result[start] == '0') {
start++;
}
// Construct the final result string
return start == top ? "0" : new string(result, start, top - start);
}
}
반응형
'PROGRAMING > C#' 카테고리의 다른 글
[Algorithm] Determine matching parentheses (3) | 2024.05.15 |
---|---|
[Algorithm] Sort Colors (3) | 2024.05.04 |
[Algorithm] Reverse each word (5) | 2024.05.02 |
[Algorithm] Valid Palindrome (69) | 2024.04.30 |
[Algorithm] Palindrome Number (92) | 2024.04.27 |