Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time Complexity: O(N)
- Space Complexity: O(N)
- N = Length of the num string.
- */
- class Solution {
- public String removeKdigits(String num, int k) throws IllegalArgumentException {
- if (num == null) {
- throw new IllegalArgumentException("Input num string is null");
- }
- if (num.length() == 0 || num.length() <= k) {
- return "0";
- }
- if (k == 0) {
- return num;
- }
- StringBuilder sb = new StringBuilder();
- for (char c : num.toCharArray()) {
- while (k > 0 && sb.length() != 0 && sb.charAt(sb.length()-1) > c) {
- sb.setLength(sb.length()-1);
- k--;
- }
- if (sb.length() == 1 && sb.charAt(0) == '0') {
- sb.setCharAt(0, c);
- } else {
- sb.append(c);
- }
- }
- if (k > 0) {
- sb.setLength(sb.length() - k);
- }
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement