【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
Python
:s.startswith(word)
Java
:s.startsWith(word)
Golang
:strings.HasPrefix(s, word)
计数即为统计words
中有多少个word
是s
的前缀:
使用一个变量
ans
,初始值为0
,在遍历words
字符串数组的时候更新ans
值就行了。
- 时间复杂度 O ( m n ) O(mn) O(mn),其中 m = l e n ( w o r d s ) , n = l e n ( s ) m=len(words), n=len(s) m=len(words),n=len(s)
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
/*
* @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
'''
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
/*
* @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
/*
* @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和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源