Leetcode 1967. Number of Strings That Appear as Substrings in Word
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".
patterns
array and the word
string?patterns
and word
?Assumptions:
patterns
is <= 10^4.patterns
.word
.word
.To determine if one string is a substring of another, we can use the contains
method of the String
class in Java.
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
}
}
patterns
contains
method in Java is O(m) where m is the length of the substring to be matched in the worst case. Given that the sum of the length of all strings in patterns
is <= 10^4, this approach is efficient for competitive programming.This solution should efficiently solve the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?