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)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值