置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年6月29日 星期一

LeetCode 解題筆記:1967. Number of Strings That Appear as Substrings in Word

作者:王一哲
日期:2026年6月29日


LeetCode 題目連結:1967. Number of Strings That Appear as Substrings in Word

解題想法


簡單題。這題用 Python 很簡單,用 sum, for, in 搭配可以一行解。用 C++ 解題可以用 find 找 pattern 是否出現在 word 之中,如果有找到就將答案 cnt 加 1。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.21 MB, beats 58.44%.
class Solution:
    def numOfStrings(self, patterns: List[str], word: str) -> int:
        return sum(patter in word for patter in patterns)


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 11.80 MB, beats 33.74%.
class Solution {
public:
    int numOfStrings(vector<string>& patterns, string word) {
        int cnt = 0;
        for(auto pattern : patterns) {
            if (word.find(pattern) != string::npos) cnt++;
        }
        return cnt;
    }
};

沒有留言:

張貼留言