置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年6月13日 星期六

LeetCode 解題筆記:3838. Weighted Word Mapping

作者:王一哲
日期: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)
        


C++ 程式碼


Runtime: 0 ms, beats 100%. Memory: 43.85 MB, beats 17.26%.
class Solution {
public:
    string mapWordWeights(vector<string>& words, vector<int>& weights) {
        char table[26] = 
            {'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'};
        
        string s;
        for(auto word : words) {
            int tot = 0;
            for(auto c : word) {
                tot += weights[c - 'a'];
            }
            s += table[tot % 26];
        }
        return s;
    }
};

Runtime: 0 ms, beats 100%. Memory: 43.81 MB, beats 17.26%.
class Solution {
public:
    string mapWordWeights(vector<string>& words, vector<int>& weights) {
        string s;
        for(auto word : words) {
            int tot = 0;
            for(auto c : word) {
                tot += weights[c - 'a'];
            }
            s += char(25 - tot % 26 + 'a');
        }
        return s;
    }
};


沒有留言:

張貼留言