精華區beta Marginalman 關於我們 聯絡資訊
題目 有一個字串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