【算法】2185. 统计包含给定前缀的字符串(多语言实现)

105 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 6 天,点击查看活动详情


2185. 统计包含给定前缀的字符串:

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

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 新的语言,对于字符串一般都有前缀判断的API方法,直接用吧。

题解

rust

impl Solution {
    pub fn prefix_count(words: Vec<String>, pref: String) -> i32 {
        words.iter().filter(|s| {
            s.starts_with(&pref)
        }).count() as i32
    }
}

go

func prefixCount(words []string, pref string) int {
    ans := 0

    for _, word := range words {
        if strings.HasPrefix(word, pref) {
            ans++
        }
    }

    return ans
}

c++

class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int ans = 0;

        for (string &word: words) {
            if (word.find(pref) == 0) {
                ++ans;
            }
        }

        return ans;
    }
};

java

class Solution {
    public int prefixCount(String[] words, String pref) {
        int ans = 0;

        for (String word : words) {
            if (word.startsWith(pref)) {
                ++ans;
            }
        }

        return ans;
    }
}

python

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


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~


开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 6 天,点击查看活动详情