# Simple Java Solution

• Do the following logic time and time again until there is nonum[i] > num[i + 1] exists or until we've already deleted all k digits.

Always search from the beginning:
if num[i] > num[i + 1]
delete num[i] and counter++
go back to the beginning and search again

Check if we've already deleted all k digits. If not

if counter < k then delete from the back until we got counter == k

After that, check if we have leading zeroes and if yes, delete them.

Last, return result.

public class Solution {
public String removeKdigits(String num, int k) {
if (k == num.length()) return "0";
StringBuilder sb = new StringBuilder(num);
int cnt = 0;
int l = num.length();
boolean flag = true;
while (flag && cnt < k) {
flag = false;
for (int i = 0; i < l - 1; i++) {
if (sb.charAt(i) > sb.charAt(i + 1)) {
flag = true;
sb.deleteCharAt(i);
l--;
cnt++;
break;
}
}
}
while (cnt < k) {
sb.deleteCharAt(sb.length() - 1);
cnt++;
}
String res = sb.toString();
int i = 0;
for (; i < res.length(); i++) {
if (res.charAt(i) != '0') {
break;
}
if (i == res.length() - 1) return "0";
}
res = res.substring(i);
return res;
}
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.