LeetCode 75

Removing Stars From a String

Problem
LC 2390
Topic
Stack
File
official75_LC2390RemovingStarsFromAString.java
Path
pkg5leetcode/official75/official75_LC2390RemovingStarsFromAString.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC2390RemovingStarsFromAString.java
Approach
Stack push chars; pop on star.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC2390RemovingStarsFromAString.java
1package pkg5leetcode.official75;2 3/*4 * Removing Stars From a String | LC 23905 * APPROACH: Stack push chars; pop on star.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC2390RemovingStarsFromAString {11    static String removeStars(String s) {12        Deque<Character> st = new ArrayDeque<>();13        for (char c : s.toCharArray()) {14            if (c == '*') st.pollLast();15            else st.addLast(c);16        }17        StringBuilder sb = new StringBuilder();18        for (char c : st) sb.append(c);19        return sb.toString();20    }21 22    public static void main(String[] args) {23        check("le".equals(removeStars("leet**")), "case1");24        check("".equals(removeStars("erase*****")), "case2");25        System.out.println("all tests passed");26    }27 28    static void check(boolean cond, String name) {29        if (!cond) throw new AssertionError("FAILED: " + name);30        System.out.println("  PASS " + name);31    }32}