-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveKDigits.java
More file actions
35 lines (35 loc) · 1.02 KB
/
RemoveKDigits.java
File metadata and controls
35 lines (35 loc) · 1.02 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
import java.util.*;
public class RemoveKDigits{
public static String updatedString(String str, int k){
Stack<Character> s = new Stack<>();
for(int i=0;i<str.length();i++){
while(!s.isEmpty() && k>0 && s.peek()-'0'>str.charAt(i)-'0'){
s.pop();
k--;
}
s.push(str.charAt(i));
}
while(k>0){
s.pop();
k--;
}
StringBuilder sb = new StringBuilder("");
while(!s.isEmpty()){
sb.append(s.peek());
s.pop();
}
sb.reverse();
while(sb.length()>1 && sb.charAt(0)=='0'){
sb.deleteCharAt(0);
}
return sb.toString();
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
String str=sc.nextLine();
System.out.print("Enter the number of digits: ");
int k=sc.nextInt();
System.out.println(updatedString(str,k));
}
}