Skip to content

Latest commit

 

History

History
125 lines (92 loc) · 2.82 KB

File metadata and controls

125 lines (92 loc) · 2.82 KB

English Version

题目描述

给你一个字符串数组 words 和一个字符串 pref

返回 words 中以 pref 作为 前缀 的字符串的数目。

字符串 s前缀 就是  s 的任一前导连续字符串。

 

示例 1:

输入:words = ["pay","attention","practice","attend"], pref = "at"
输出:2
解释:以 "at" 作为前缀的字符串有两个,分别是:"attention" 和 "attend" 。

示例 2:

输入:words = ["leetcode","win","loops","success"], pref = "code"
输出:0
解释:不存在以 "code" 作为前缀的字符串。

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length, pref.length <= 100
  • words[i]pref 由小写英文字母组成

解法

Python3

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        return sum(w.startswith(pref) for w in words)

Java

class Solution {
    public int prefixCount(String[] words, String pref) {
        int ans = 0;
        for (String w : words) {
            if (w.startsWith(pref)) {
                ++ans;
            }
        }
        return ans;
    }
}

TypeScript

function prefixCount(words: string[], pref: string): number {
    const n = pref.length;
    let ans = 0;
    for (let str of words) {
        if (str.substring(0, n) == pref) {
            ans++;
        }
    }
    return ans;
}

C++

class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int ans = 0;
        for (auto& w : words)
            if (w.find(pref) == 0)
                ++ans;
        return ans;
    }
};

Go

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

...