-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveKDigits.java
More file actions
52 lines (42 loc) · 1.15 KB
/
RemoveKDigits.java
File metadata and controls
52 lines (42 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Leetcode;
import java.util.Stack;
public class RemoveKDigits
{
public static void main( String[] args )
{
RemoveKDigits obj = new RemoveKDigits();
System.out.println( obj.removeKdigits( "9", 1 ) );
}
public String removeKdigits(String num, int k) {
int count=k;
Stack<Integer> stack = new Stack();
for(int i=0;i<num.length();i++)
{
int n = num.charAt(i)-'0';
while(!stack.isEmpty() && n<stack.peek() && count>0)
{
stack.pop();
count--;
}
stack.push(n);
}
while(count>0)
{
stack.pop();
count--;
}
StringBuilder result = new StringBuilder();
while(!stack.isEmpty())
{
result.append(stack.pop());
}
result.reverse();
while(result.length()>1 && result.charAt(0)=='0')
{
result.deleteCharAt(0);
}
if(result.length()==0)
result.append( "0");
return result.toString();
}
}