1 Star 0 Fork 332

傍地走 / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.85 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2022-08-13 22:42 . style: format all python code

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

English Version

题目描述

给你一个字符串数组 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  包含小写英文字母。

解法

Python3

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

Java

class Solution {
    public int countPrefixes(String[] words, String s) {
        int ans = 0;
        for (String word : words) {
            if (word.equals(s.substring(0, Math.min(s.length(), word.length())))) {
                ++ans;
            }
        }
        return ans;
    }
}

C++

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

Go

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

TypeScript

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/noodlesAI/leetcode.git
git@gitee.com:noodlesAI/leetcode.git
noodlesAI
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891