作者Meaverzt (單推凜寶)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Mon Jan 13 13:11:01 2025
題目
有一個字串s
對每個index我們都要找左邊跟右邊最近出現過的s[index]把他刪掉
如果沒有就不用理他
最後回傳字串的長度
思路:
去計算每個字出現過幾遍
總共會有三種情況
1.出現少於3遍:沒辦法繼續簡化 答案長度加上出現的次數
2.出現奇數遍:因為每次簡化長度會減2 所以最後答案長度+1 eg:aaaaa最後會只剩a
3.出現偶數遍:答案長度+2 eg:aaaa最後會剩aa
每個字跑完長度加起來就是答案了
Code:
class Solution(object):
def minimumLength(self, s):
dict={}
for i in s:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
ans=0
for i in dict:
if dict[i]<3:
ans+=dict[i]
else:
ans+=2 if dict[i]%2==0 else 1
return ans
--
https://i.imgur.com/5XtXJd3.jpeg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.237.36.8 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1736745063.A.8EB.html
→ Furina: 大師 01/13 13:11
推 jimmy888: 剩我不會寫程式了 01/13 13:29