LeetCode problem#2390
Removing Stars From a String
Solved in 1 languageJava
Solution
29 lines
1class Solution {
2 // time O(n)
3 // space O(n)
4 public String removeStars(String s) {
5 Stack<Character> stack = new Stack<Character>();
6
7 for (int i = 0; i < s.length(); i++) {
8 char c = s.charAt(i);
9
10 if (c == '*') {
11 if (!stack.isEmpty()) {
12 stack.pop();
13 }
14 }
15 else {
16 stack.push(c);
17 }
18 }
19
20
21 StringBuilder sb = new StringBuilder(stack.size());
22 sb.setLength(stack.size());
23 for (int i = stack.size() - 1; i >= 0; i--) {
24 sb.setCharAt(i, stack.pop());
25 }
26
27 return sb.toString();
28 }
29}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.