2390. Removing Stars From a String
Problem
Each * in s removes itself and the closest non-star character to its left. Return the string after processing every star (this is always possible).
Example: "leet**cod*e" → "lecoe"
Each * deletes the closest non-star character to its left — exactly a stack pop. Push letters, pop on *.
Complexity: O(n).
class Solution:
def removeStars(self, s: str) -> str:
st = []
for ch in s:
if ch == "*":
st.pop()
else:
st.append(ch)
return "".join(st)
assert Solution().removeStars("leet**cod*e") == "lecoe"
assert Solution().removeStars("erase*****") == ""
assert Solution().removeStars("abc") == "abc"
class Solution {
public String removeStars(String s) {
StringBuilder st = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '*') st.setLength(st.length() - 1);
else st.append(c);
}
return st.toString();
}
}
func removeStars(s string) string {
st := []byte{}
for i := 0; i < len(s); i++ {
if s[i] == '*' {
st = st[:len(st)-1]
} else {
st = append(st, s[i])
}
}
return string(st)
}