Skip to content

2390. Removing Stars From a String 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  string removeStars(string s) {
    string ans;
    for (const char c : s)
      if (c == '*')
        ans.pop_back();
      else
        ans.push_back(c);
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public String removeStars(String s) {
    StringBuilder sb = new StringBuilder();
    for (final char c : s.toCharArray())
      if (c == '*')
        sb.deleteCharAt(sb.length() - 1);
      else
        sb.append(c);
    return sb.toString();
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def removeStars(self, s: str) -> str:
    ans = []
    for c in s:
      if c == '*':
        ans.pop()
      else:
        ans.append(c)
    return ''.join(ans)