日期:2026年6月13日
LeetCode 題目連結:3838. Weighted Word Mapping
解題想法
簡單題。先用一層 for 迴圈從串列 words 之中讀取單字 word,假設 word 對應的加總 tot = 0;再用一層 for 迴圈從 word 依序讀取字元 c,計算 c 與字母 'a' 的編號差值,將編號差值於測資 weights 之中對應的值加到 tot。最後計算 25 - tot % 26 對應的字母加到答案之中。由於 Python 的字串操作速度較慢,我是先將字母存到串列 arr 之中,最後再用 join 將 arr 的內容組成字串後回傳。
後來我又想到,如果先建好一個反序的字母對照表,最後從 tot 的值找出對應字母的速度應該會快一點,沒想到這個方法大約需要 9 ms,直接用算的只要 4 ms,有點意外。
Python 程式碼
Runtime: 4 ms, beats 91.63%. Memory: 19.34 MB, beats 33.64%.
class Solution:
def mapWordWeights(self, words: List[str], weights: List[int]) -> str:
arr = []
for word in words:
tot = 0
for c in word:
tot += weights[ord(c) - ord('a')]
arr.append(chr(25 - tot % 26 + ord('a')))
return "".join(arr)
Runtime: 9 ms, beats 56.74%. Memory: 19.36 MB, beats 33.64%.
class Solution:
def mapWordWeights(self, words: List[str], weights: List[int]) -> str:
table = ('z', 'y', 'x', 'w', 'v',
'u', 't', 's', 'r', 'q',
'p', 'o', 'n', 'm', 'l',
'k', 'j', 'i', 'h', 'g',
'f', 'e', 'd', 'c', 'b', 'a')
arr = []
for word in words:
tot = 0
for c in word:
tot += weights[ord(c) - ord('a')]
arr.append(table[tot % 26])
return "".join(arr)