【算法】1967. 作为子字符串出现在单词中的字符串数目(多语言实现)

112 阅读2分钟

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


1967. 作为子字符串出现在单词中的字符串数目:

给你一个字符串数组 patterns 和一个字符串 word ,统计 patterns 中有多少个字符串是 word 的子字符串。返回字符串数目。

子字符串 是字符串中的一个连续字符序列。

样例 1:

输入:
	patterns = ["a","abc","bc","d"], word = "abc"
	
输出:
	3
	
解释:
	- "a""abc" 的子字符串。
	- "abc""abc" 的子字符串。
	- "bc""abc" 的子字符串。
	- "d" 不是 "abc" 的子字符串。
	patterns 中有 3 个字符串作为子字符串出现在 word 中。

样例 2:

输入:
	patterns = ["a","b","c"], word = "aaaaabbbbb"
	
输出:
	2
	
解释:
	- "a""aaaaabbbbb" 的子字符串。
	- "b""aaaaabbbbb" 的子字符串。
	- "c" 不是 "aaaaabbbbb" 的字符串。
	patterns 中有 2 个字符串作为子字符串出现在 word 中。

样例 3:

输入:
	patterns = ["a","a","a"], word = "ab"
	
输出:
	3
	
解释:
	patterns 中的每个字符串都作为子字符串出现在 word "ab" 中。

提示:

  • 1 <= patterns.length <= 100
  • 1 <= patterns[i].length <= 100
  • 1 <= word.length <= 100
  • patterns[i] 和 word 由小写英文字母组成

原题传送门:

leetcode.cn/problems/nu…


分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 虽然可以用KMP算法,但是API不是更好用吗。

题解

rust

impl Solution {
    pub fn num_of_strings(patterns: Vec<String>, word: String) -> i32 {
        patterns.iter().filter(|&p| {
            word.contains(p)
        }).count() as i32
    }
}

go

func numOfStrings(patterns []string, word string) int {
    ans := 0

    for _, p := range patterns {
        if strings.Contains(word, p) {
            ans++
        }
    }

    return ans
}

c++

class Solution {
public:
    int numOfStrings(vector<string>& patterns, string word) {
        int ans = 0;

        for (string& p : patterns) {
            if (word.find(p) != string::npos) {
                ++ans;
            }
        }

        return ans;
    }
};

java

class Solution {
    public int numOfStrings(String[] patterns, String word) {
        int ans = 0;

        for (String p : patterns) {
            if (word.contains(p)) {
                ++ans;
            }
        }

        return ans;
    }
}

python

class Solution:
    def numOfStrings(self, patterns: List[str], word: str) -> int:
        ans = 0
        for p in patterns:
            if p in word:
                ans += 1
        return ans


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


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