मुख्य कंटेंट तक स्किप करें

Removing Stars From a String

KANISHKA GUPTA
EditReport

Removing Stars From a String

Description

You are given a string s, which contains stars *.

In one operation, you can:

  • Choose a star in s.
  • Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

  • The input will be generated such that the operation is always possible.
  • It can be shown that the resulting string will always be unique.

Video Explanation

Approach

To solve this problem, we can use a stack to keep track of the non-star characters. We iterate through the string, and for each character:

  1. If it is a non-star character, push it onto the stack.
  2. If it is a star (*), pop the top element from the stack (i.e., remove the closest non-star character).

Finally, the remaining elements in the stack represent the string after all stars and corresponding characters have been removed.

Solutions

class Solution {
public:
string removeStars(string s) {
string res = "";
for (char c : s) {
if (c == '*') {
if (!res.empty()) res.pop_back();
} else {
res.push_back(c);
}
}
return res;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Removing Stars From a String"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.