堆疊應用+模擬: 移除字串中的星號_Leetcode 精選75題解析

2024/02/29閱讀時間約 4 分鐘

題目敘述

題目會給我們一個字串s。

要求我們移除字串中的星號,還有刪除星號左手邊最靠近的第一個字元

以字串的形式返回輸出答案。

題目的原文敘述


測試範例

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:

  • 1 <= s.length <= 10^5

字串s的長度介於 1 ~ 10^5 之間。

  • s consists of lowercase English letters and stars *.

字串s只會包含小寫英文字母 和 *星號。

  • The operation above can be performed on s.

定義中的操作可以在字串s中完成。


演算法

這題的關鍵在於把 *星號 當成我們平常鍵盤上使用的←Backsapce鍵的功能,向左邊吃掉一個最靠近的字元

實作的時候,先建立一個空的stack,把每個字元依序推入stack
假如遇到 *星號,則直接pop stack頂端的字元,相當於滿足題目所說的「向左邊吃掉一個最靠近的字元」。

最後,把stack內剩餘的字元轉成字串的形式輸出答案即可。


程式碼

class Solution:
def removeStars(self, s: str) -> str:

stk = []

# scan each character from left to right
for char in s:

if char != '*':
# push current character into stack
stk.append( char )

else:
# pop one character from stack, removed with * together.
stk.pop()

return "".join(stk)

以行動支持創作者!付費即可解鎖
本篇內容共 1712 字、0 則留言,僅發佈於Leetcode 精選75題 上機考面試題 詳解你目前無法檢視以下內容,可能因為尚未登入,或沒有該房間的查看權限。
45會員
288內容數
由有業界實戰經驗的演算法工程師, 手把手教你建立解題的框架, 一步步寫出高效、清晰易懂的解題答案。 著重在讓讀者啟發思考、理解演算法,熟悉常見的演算法模板。 深入淺出地介紹題目背後所使用的演算法意義,融會貫通演算法與資料結構的應用。 在幾個經典的題目融入一道題目的多種解法,或者同一招解不同的題目,擴展廣度,並加深印象。
留言0
查看全部
發表第一個留言支持創作者!