
题目描述
给你一个字符串数组 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
只 包含小写英文字母。
解法
方法一:遍历计数
我们直接遍历数组 \(\textit{words}\),对于每个字符串 \(w\),判断 \(s\) 是否以 \(w\) 为前缀,如果是则答案加一。
遍历结束后,返回答案即可。
时间复杂度 \(O(m \times n)\),其中 \(m\) 和 \(n\) 分别是数组 \(\textit{words}\) 的长度和字符串 \(s\) 的长度。空间复杂度 \(O(1)\)。
| class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return sum(s.startswith(w) for w in words)
|
| class Solution {
public int countPrefixes(String[] words, String s) {
int ans = 0;
for (String w : words) {
if (s.startsWith(w)) {
++ans;
}
}
return ans;
}
}
|
| class Solution {
public:
int countPrefixes(vector<string>& words, string s) {
int ans = 0;
for (auto& w : words) {
ans += s.starts_with(w);
}
return ans;
}
};
|
| func countPrefixes(words []string, s string) (ans int) {
for _, w := range words {
if strings.HasPrefix(s, w) {
ans++
}
}
return
}
|
| function countPrefixes(words: string[], s: string): number {
return words.filter(w => s.startsWith(w)).length;
}
|
| impl Solution {
pub fn count_prefixes(words: Vec<String>, s: String) -> i32 {
words.iter().filter(|w| s.starts_with(w.as_str())).count() as i32
}
}
|
| public class Solution {
public int CountPrefixes(string[] words, string s) {
return words.Count(w => s.StartsWith(w));
}
}
|