Skip to content

Instantly share code, notes, and snippets.

@h0tk3y
Created February 5, 2025 18:11
Show Gist options
  • Save h0tk3y/4c6e237d24391652e9389be710ebc23f to your computer and use it in GitHub Desktop.
Save h0tk3y/4c6e237d24391652e9389be710ebc23f to your computer and use it in GitHub Desktop.
Remove k digits - shortened
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