Created
November 14, 2024 20:04
-
-
Save ghadj/7739b7121bd6aa91eecbbf85b391942f to your computer and use it in GitHub Desktop.
Leetcode #2390
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * --- | |
| * [https://leetcode.com/problems/removing-stars-from-a-string] | |
| * 2390. Removing Stars From a String | |
| * You are given a string s, which contains stars *. | |
| * | |
| * In one operation, you can: | |
| * - Choose a star in s. | |
| * - Remove the closest non-star character to its left, as well as remove the star itself. | |
| * | |
| * Return the string after all stars have been removed. | |
| * --- | |
| */ | |
| class Solution { | |
| public String removeStars(String s) { | |
| char c; | |
| int count = 0; | |
| int index; | |
| Stack<Character> stack = new Stack<>(); | |
| for (index = s.length()-1; index >= 0; index--) { | |
| c = s.charAt(index); | |
| if (c == '*') { | |
| count++; | |
| } else if (count > 0) { | |
| count--; | |
| } else { | |
| stack.push(c); | |
| } | |
| } | |
| index = 0; | |
| char[] result = new char[stack.size()]; | |
| while(!stack.isEmpty()) { | |
| result[index++] = stack.pop(); | |
| } | |
| return String.copyValueOf(result); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment