2255 统计是给定字符串前缀的字符串数目

·   ·   ·   ·

  ·   ·


题目链接

2255. 统计是给定字符串前缀的字符串数目

分析

遍历 $words$ 中的每一个字符串毕竟即可

代码实现

class Solution {
public:
    int countPrefixes(vector<string>& words, string s) {
        int ans = 0;
        auto isPrefix = [&](string t) {
            if(t.size() > s.size())
                return false;
      
            for(int i = 0; i < t.size(); ++i)
                if(s[i] != t[i])
                    return false;
      
            return true;
        };

        for(string word : words) {
            if(isPrefix(word))
                ans++;
        }

        return ans;
    }
};

复杂度分析

  • 时间复杂度:$O(nm)$,$n$ 为 $s$ 的长度,$m$ 为 $words$ 中字符串长度的总和
  • 空间复杂度:$O(1)$