You are given a string (s), which contains stars (*).
In one operation, you can:
Return the string after all stars have been removed.
Note:
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
Constraints:
class Solution:
def removeStars(self, s: str) -> str:
if not s:
return ''
stack = []
for char in s:
if char == '*':
stack.pop()
else:
stack.append(char)
return ''.join(stack)
Empty String Check:
Making a Stack:
Going Through the String:
If It’s a Star:
If It’s a Letter:
Putting It All Together:
function removeStars(s: string): string {
if (!s) {
return '';
}
const stack: string[] = [];
for (const char of s) {
if (char === '*') {
stack.pop();
} else {
stack.push(char);
}
}
return stack.join('');
}
Is it Empty?
Making a Special Box:
Looking at Each Thing:
Star Sticker!
It’s a Letter!
Putting Them Together:
func removeStars(s string) string {
if len(s) == 0 {
return ""
}
stack := []rune{}
for _, char := range s {
if char == '*' {
if len(stack) > 0 {
stack = stack[:len(stack)-1]
}
} else {
stack = append(stack, char)
}
}
return string(stack)
}
Is it Empty?
Making a Special Box:
Looking at Each Thing:
Star Sticker!
It’s a Letter!
Putting Them Together:
If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.
Muchas gracias!
Follow me for more content like this.
X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium
Down below you can find other ways to tip my work.
BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"