-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemovingStarsFromString.java
More file actions
110 lines (81 loc) · 2.46 KB
/
RemovingStarsFromString.java
File metadata and controls
110 lines (81 loc) · 2.46 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package Algorithms.StackAlgos;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 16 April 2025
*/
public class RemovingStarsFromString {
public static void main(String[] args) {
String s = "leet**cod*e";
System.out.println(removeStars(s));
}
public static String removeStars(String s) {
Stack<Character> stack = new Stack<>();
for (char c: s.toCharArray()) {
if(c=='*') {
if(!stack.isEmpty()) stack.pop();
}
else stack.push(c);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) sb.append(stack.pop());
return sb.reverse().toString();
}
public static String removeStars1(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '*') {
if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String removeStarsUsingDeque(String s) {
Deque<Character> st = new ArrayDeque<>();
int len = s.length();
for(int i = 0 ; i < len ; i++){
char ch = s.charAt(i);
if(ch == '*'){
st.pop();
continue;
}
st.push(ch);
}
StringBuffer str = new StringBuffer();
while(!st.isEmpty()){
char el = st.pollLast();
str.append(el);
}
return str.toString();
}
public String removeStarsMyApproach(String s) {
Stack<Character> stack = new Stack<>();
for(char c: s.toCharArray()) stack.push(c);
StringBuilder sb = new StringBuilder();
char c = stack.pop();
int rm=0;
while(!stack.isEmpty()) {
// count *s
while(!stack.isEmpty() && c=='*') {
rm++;
c=stack.pop();
}
// remove *s chars
while(rm>0 && c!='*'){
c= stack.isEmpty()? '0' : stack.pop();
rm--;
}
// fill next non *s
while(!stack.isEmpty() && c!='*') {
sb.append(c);
c=stack.pop();
}
}
if(c!='*' && c !='0') sb.append(c);
return sb.reverse().toString();
}
}