ZhongKuo0228 / study

0 stars 0 forks source link

2390. Removing Stars From a String #82

Open fockspaces opened 10 months ago

fockspaces commented 10 months ago
  1. 用 stack 概念
  2. 遇到星星則刪最後一個
  3. 否則,append char
class Solution:
    def removeStars(self, s: str) -> str:
        ans = ""
        for c in s:
            if c == '*':
                ans = ans[:-1]
            else:
                ans += c
        return ans
fockspaces commented 10 months ago

GPT improve: 用 stack 實作,string concatenation 效率不好

class Solution:
    def removeStars(self, s: str) -> str:
        stack = []
        for c in s:
            if c == '*' and stack:
                    stack.pop()
            else:
                stack.append(c)
        return "".join(stack)