精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/string-compression-iii 3163. String Compression III 給一個字串 word 回傳壓縮後的字串 comp 首先給一個空字串 comp 當 word 非空時 1. 刪除最多9個由單一字元 c 組成的前綴 2. 把數量與字元 c 加到 comp Example 1: Input: word = "abcde" Output: "1a1b1c1d1e" Example 2: Input: word = "aaaaaaaaaaaaaabb" Output: "9a5a2b" Constraints: 1 <= word.length <= 2 * 10^5 word 只包含小寫英文字母 思路: 照著做就好了 最後一次的記得要補上 Python Code: class Solution: def compressedString(self, word: str) -> str: comp = '' current_char = word[0] cnt = 1 for w in word[1:]: if w == current_char and cnt < 9: cnt += 1 else: comp += f'{cnt}{current_char}' cnt = 1 current_char = w comp += f'{cnt}{current_char}' return comp 原本用 comp = [] 跟 return ''.join(comp) 不過結果上來說直接改字串空間花更少 時間則差不多 是數量不多的原因嗎 JavaScript 用直接改字串則比開 array 快了一半的時間 23 ms / 47 ms 不過也有可能是 leetcode 自己的問題 (( -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.55.73 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1730695928.A.61F.html