From b4458cd16ec87a35712930d79863e23e562bde78 Mon Sep 17 00:00:00 2001 From: Saikat Kar Date: Fri, 1 Apr 2022 15:38:34 +0530 Subject: [PATCH] Time: 69 ms (14.18%), Space: 48.3 MB (20.16%) - LeetHub --- 402-remove-k-digits/402-remove-k-digits.java | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 402-remove-k-digits/402-remove-k-digits.java diff --git a/402-remove-k-digits/402-remove-k-digits.java b/402-remove-k-digits/402-remove-k-digits.java new file mode 100644 index 0000000..d2aa681 --- /dev/null +++ b/402-remove-k-digits/402-remove-k-digits.java @@ -0,0 +1,31 @@ +class Solution { + public String removeKdigits(String num, int k) { + Stack stack = new Stack<>(); + char[] numArr = num.toCharArray(); + for (int i = 0; i < numArr.length; i++) { + while (!stack.isEmpty() && stack.peek() > numArr[i] && k > 0) { + stack.pop(); + k--; + } + stack.push(numArr[i]); + } + + while (k > 0 && !stack.isEmpty()) { + stack.pop(); + k--; + } + Stack tempStack = new Stack<>(); + while (!stack.isEmpty()) { + tempStack.push(stack.pop()); + } + while(!tempStack.isEmpty() && tempStack.peek() == '0') { + tempStack.pop(); + } + char [] result = new char[tempStack.size()]; + int i = 0; + while (!tempStack.isEmpty()) { + result[i++] = tempStack.pop(); + } + return result.length == 0 ? "0" : String.valueOf(result); + } +} \ No newline at end of file