Skip to content

Commit defa0bc

Browse files
Merge pull request #2723 from achintw/Create-2390-Removing-Stars-From-a-String.java
Create 2390-Removing-Stars-From-a-String.java
2 parents a90df98 + d4b120b commit defa0bc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public String removeStars(String s) {
3+
4+
// Create a new stack to keep track of characters encountered so far
5+
Stack<Character> stk = new Stack<>();
6+
7+
// Iterate over each character in the input string
8+
for (char c : s.toCharArray()) {
9+
// If the current character is a star,
10+
// remove the topmost character from the stack
11+
if (c == '*') {
12+
stk.pop();
13+
}
14+
// If the current character is not a star, add it to the stack
15+
else {
16+
stk.push(c);
17+
}
18+
}
19+
20+
// StringBuilder to store the characters in the stack
21+
StringBuilder sb = new StringBuilder();
22+
for (char c : stk) {
23+
sb.append(c);
24+
}
25+
26+
// Convert the StringBuilder to a string and return it as the output
27+
return sb.toString();
28+
}
29+
}

0 commit comments

Comments
 (0)