| 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 | } |