Re: [閒聊] 每日LeetCode
2390. Removing Stars From a String
給你一個包含 '*' 的字串,執行以下操作後回傳結果
1.挑一個 '*',移除他和他左邊第一個非 '*' 的字元
2.重複 1. 直到字串中沒有 '*'
input string 會保證每個 '*' 都找的到消除對象
另外不管移除順序為何結果都會一樣
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
Example 2:
Input: s = "erase*****"
Output: ""
思路:
1.看到移除左邊第一個應該很容易能想到用 stack
從左到右把字串放進 stack 裡 遇到 '*' 就直接 pop 掉 stack 頂部就好
'*' 不會進 stack 所以不用額外判斷
Python code:
class Solution:
def removeStars(self, s: str) -> str:
stk = []
for c in s:
if c == '*':
stk.pop()
else:
stk.append(c)
return ''.join(stk)
--
蛤?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.252.3.181 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1681193153.A.606.html
推
04/11 16:39,
2年前
, 1F
04/11 16:39, 1F
推
04/11 19:59,
2年前
, 2F
04/11 19:59, 2F
討論串 (同標題文章)
完整討論串 (本文為第 291 之 719 篇):