Re: [閒聊] 每日leetcode
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/10/07 17:55)推噓0(0推 0噓 0→)留言0則, 0人參與討論串957/1548 (看更多)
https://leetcode.com/problems/minimum-string-length-after-removing-substrings
2696. Minimum String Length After Removing Substrings
有一個由大寫英文字母組成的字串 s
每次操作可以將字串中出現的"AB"或"CD"刪除
回傳結果字串的最小可能長度
Note: 刪除子字串後字串會連接起來 可能產生新的"AB"或"CD"
Example 1:
Input: s = "ABFCACDB"
Output: 2
Explanation: 移除"AB" > 移除"CD" > 移除"AB" > 剩下"FC" 回傳2
Example 2:
Input: s = "ACBBD"
Output: 5
Explanation: 沒有可刪除的"AB"或"CD" 回傳5
Constraints:
1 <= s.length <= 100
s 只包含大寫英文字母
思路:刪除
Python Code:
class Solution:
def minLength(self, s: str) -> int:
while 'AB' in s or 'CD' in s:
s = s.replace('AB', '')
s = s.replace('CD', '')
return len(s)
直接用兩次replace跟兩者各多用一次 if ... in s: 哪種比較好啊 會更快嗎
看了一下今天的太簡單沒人想寫 只好由最底層的我來了
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.30.198 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1728294920.A.75D.html
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 957 之 1548 篇):