Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in the word.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.
Example 2:
Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.
Approach
Java
public class NumberOfStrings {public static void main(String[] args) {String[] patterns = { "a", "abc", "bc", "d" };String word = "abc";System.out.println(numOfStrings(patterns, word));}static int numOfStrings(String[] patterns, String word) {int totalCount = 0;for (int i = 0; i < patterns.length; i++) {if (word.contains(patterns[i]))totalCount++;}return totalCount;}}
Output:
3
C++
#include <bits/stdc++.h>using namespace std;int numOfStrings(vector<string> &patterns, string word){int totalCount = 0;for (int i = 0; i < patterns.size(); i++){if (word.find(patterns[i]) != string::npos)totalCount++;}return totalCount;}int main(){vector<string> patterns = {"a", "abc", "bc", "d"};string word = "abc";cout << numOfStrings(patterns, word) << "\n";return 0;}
Output:
3
No comments:
Post a Comment