algoadvance

Leetcode 1967. Number of Strings That Appear as Substrings in Word

Problem Statement

You are given an array of strings patterns and a string word. You need to determine how many strings in patterns appear as substrings in word.

Return the number of strings in patterns that appear as substrings in word.

Example:

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".

Clarifying Questions

  1. What is the length constraint for the patterns array and the word string?
  2. Are there any specific characters allowed or disallowed in patterns and word?
  3. Should the substring matching be case-sensitive?

Assumptions:

Strategy

  1. Loop through each pattern in patterns.
  2. Check if each pattern is a substring in word.
  3. Keep a count of how many patterns are substrings in word.
  4. Return the count.

To determine if one string is a substring of another, we can use the contains method of the String class in Java.

Code

import java.util.List;

public class Solution {
    public int numOfStrings(String[] patterns, String word) {
        int count = 0;
        for (String pattern : patterns) {
            if (word.contains(pattern)) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        String[] patterns = {"a","abc","bc","d"};
        String word = "abc";
        System.out.println(sol.numOfStrings(patterns, word)); // Output: 3
    }
}

Time Complexity

This solution should efficiently solve the problem within the given constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI