Number of Strings That Appear as Substrings in Word

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.

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[] patternsString 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&patternsstring word)
{
    int totalCount = 0;

    for (int i = 0i < patterns.size(); i++)
    {
        if (word.find(patterns[i]) != string::npos)
            totalCount++;
    }
    return totalCount;
}

int main()
{
    vector<stringpatterns = {"a""abc""bc""d"};
    string word = "abc";

    cout << numOfStrings(patternsword<< "\n";

    return 0;
}

Output:

3


No comments:

Post a Comment