Remove Star Characters From a String

medium string stack

Problem

A '*' character acts as a backspace: it deletes the closest non-star character to its left. Return the final string after every star has been processed. Use a stack: push letters, pop on stars.

Inputs = "fb*ar"
Output"far"
'*' deletes the preceding 'b'.

def remove_stars(s):
    out = []
    for c in s:
        if c == '*': out.pop()
        else: out.append(c)
    return "".join(out)
function removeStars(s) {
  const out = [];
  for (const c of s) {
    if (c === '*') out.pop();
    else out.push(c);
  }
  return out.join("");
}
class Solution {
    public String removeStars(String s) {
        StringBuilder out = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '*') out.deleteCharAt(out.length() - 1);
            else out.append(c);
        }
        return out.toString();
    }
}
string removeStars(string s) {
    string out = "";
    for (char c : s) {
        if (c == '*') out.pop_back();
        else out += c;
    }
    return out;
}
Time: O(n) Space: O(n)