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

给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。

请你返回 words 中是字符串 s 前缀 的 字符串数目 。

一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列。

示例 1:

输入:words = [“a”,“b”,“c”,“ab”,“bc”,“abc”], s = “abc”
输出:3
解释:
words 中是 s = “abc” 前缀的字符串为:
“a” ,“ab” 和 “abc” 。
所以 words 中是字符串 s 前缀的字符串数目为 3 。

1 <= words.length <= 1000
1 <= words[i].length, s.length <= 10
words[i] 和 s 只 包含小写英文字母。

解法一:使用库函数:

class Solution {
public:
    int countPrefixes(vector<string>& words, string s) {
        int ans = 0;
        for (string &word : words) {
            if (!s.compare(0, word.size(), word)) {
                ++ans;
            }
        }

        return ans;
    }
};

如果输入数组words的长度为n,其中元素的长度为m,此算法时间复杂度为O(nm),空间复杂度为O(1)。string的compare方法的时间复杂度最多在两个字符串上都达到线性。

解法二:按题意遍历:

class Solution {
public:
    int countPrefixes(vector<string>& words, string s) {
        int ans = 0;
        for (string &word : words) {
            int wordSz = word.size();
            int i = 0;
            for (; i < wordSz; ++i) {
                if (word[i] != s[i]) {
                    break;
                }
            }

            if (i == wordSz) {
                ++ans;
            }
        }

        return ans;
    }
};

如果输入数组words的长度为n,其中元素的长度为m,此算法时间复杂度为O(nm),空间复杂度为O(1)。

posted @ 2023-02-18 01:21  epiphanyy  阅读(14)  评论(0)    收藏  举报  来源