Created
February 5, 2025 18:11
-
-
Save h0tk3y/4c6e237d24391652e9389be710ebc23f to your computer and use it in GitHub Desktop.
Remove k digits - shortened
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String removeKdigits(String num, int k) { | |
Deque<Character> resultDeque = new ArrayDeque<>(); | |
resultDeque.add(num.charAt(0)); | |
for (int i = 1; i < num.length(); ++i) { | |
var nextChar = num.charAt(i); | |
while (k > 0 && !resultDeque.isEmpty() && resultDeque.peekLast() > nextChar) { //Возвращаемся на символ назад | |
resultDeque.removeLast(); | |
k--; | |
} | |
resultDeque.add(nextChar); | |
} | |
while (k > 0) { | |
resultDeque.removeLast(); | |
k--; | |
} | |
StringBuilder builder = new StringBuilder(); | |
while (!resultDeque.isEmpty()) { | |
char ch = resultDeque.removeFirst(); | |
if (builder.length() == 0 && ch == '0') { | |
continue; | |
} | |
builder.append(ch); | |
} | |
return builder.length() == 0 ? "0" : builder.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment