Skip to content

Latest commit

 

History

History
149 lines (113 loc) · 3.5 KB

_2390. Removing Stars From a String.md

File metadata and controls

149 lines (113 loc) · 3.5 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 02, 2024

Last updated : July 01, 2024


Related Topics : String, Stack, Simulation

Acceptance Rate : 75.77 %


Solutions

Java

// Pretty good due to stringbuilder but the lack of a way to directly go to the result from stack
// is kinda annoying lol

class Solution {
    public String removeStars(String s) {
        Stack<Character> output = new Stack<>();

        for (char c : s.toCharArray()) {
            if (c == '*') {
                output.pop();
            } else {
                output.push(c);
            }
        }

        Character[] temp = new Character[output.size()];
        temp = output.toArray(temp);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < temp.length; i++) {
            sb.append(temp[i]);
        }
        

        return sb.toString();
    }
}
// 80-90% region

class Solution {
    public String removeStars(String s) {
        ArrayDeque<Character> output = new ArrayDeque<>();

        for (char c : s.toCharArray()) {
            if (c == '*') {
                output.removeLast();
            } else {
                output.addLast(c);
            }
        }

        StringBuilder sb = new StringBuilder();

        while (!output.isEmpty()) {
            sb.append(output.pop());
        } 

        return sb.toString();
    }
}
// 85-90% region!

class Solution {
    public String removeStars(String s) {
        StringBuilder sb = new StringBuilder();

        for (char c : s.toCharArray()) {
            if (c == '*') {
                sb.deleteCharAt(sb.length() - 1);
            } else {
                sb.append(c);
            }
        }
        
        return sb.toString();
    }
}

Python

# firmly in the 50% region with little variance
# From the right side using deque to skip characters


class Solution:
    def removeStars(self, s: str) -> str:
        starCounter = 0
        rightSide = deque()
        for i in reversed(s) :
            if i == '*':
                starCounter += 1
                continue
            
            if starCounter == 0 :
                rightSide.appendleft(i)
                continue
            
            starCounter -= 1

        return ''.join(list(rightSide))
# Much faster 95% region

class Solution:
    def removeStars(self, s: str) -> str:
        output = []
        
        for i in s :
            if i == '*':
                output.pop()
            else:
                output.append(i)

        return ''.join(output)