2255.统计是给定字符串前缀的字符串数目:使用库函数+计数

【LetMeFly】2255.统计是给定字符串前缀的字符串数目:使用库函数+计数

力扣题目链接:https://leetcode.cn/problems/count-prefixes-of-a-given-string/

给你一个字符串数组 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 。

示例 2:

输入:words = ["a","a"], s = "aa"
输出:2
解释:
两个字符串都是 s 的前缀。
注意,相同的字符串可能在 words 中出现多次,它们应该被计数多次。

 

提示:

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

解题方法:使用库函数+计数

很多编程语言都有判断一个字符串word是否为另一个字符串s的前缀的函数:

  • C++s.find(word) == 0
  • Pythons.startswith(word)
  • Javas.startsWith(word)
  • Golangstrings.HasPrefix(s, word)

计数即为统计words中有多少个words的前缀:

使用一个变量ans,初始值为0,在遍历words字符串数组的时候更新ans值就行了。

  • 时间复杂度$O(mn)$,其中$m=len(words), n=len(s)$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @Author: LetMeFly
* @Date: 2025-03-24 17:41:54
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-24 17:51:42
*/
class Solution {
public:
int countPrefixes(vector<string>& words, string s) {
int ans = 0;
for (string& word : words) {
ans += s.find(word) == 0;
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
'''
Author: LetMeFly
Date: 2025-03-24 17:52:11
LastEditors: LetMeFly.xyz
LastEditTime: 2025-03-24 17:52:19
'''
from typing import List

class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return sum(s.startswith(word) for word in words)

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* @Author: LetMeFly
* @Date: 2025-03-24 17:53:35
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-24 17:53:41
*/
class Solution {
public int countPrefixes(String[] words, String s) {
int ans = 0;
for (String word : words) {
ans += s.startsWith(word) ? 1 : 0;
}
return ans;
}
}

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
* @Author: LetMeFly
* @Date: 2025-03-24 17:55:08
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-24 17:55:24
*/
package main

import "strings"

func countPrefixes(words []string, s string) (ans int) {
for _, word := range words {
if strings.HasPrefix(s, word) {
ans++
}
}
return
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


2255.统计是给定字符串前缀的字符串数目:使用库函数+计数
https://blog.letmefly.xyz/2025/03/24/LeetCode 2255.统计是给定字符串前缀的字符串数目/
作者
发布于
2025年3月24日
许可协议