Ben Pereira

Posted on

# Leet Code — 1967. Number of Strings That Appear as Substrings in Word

That’s an easy problem with the description being:

Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in 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.

Example 3:
Input: patterns = ["a","a","a"], word = "ab"

Output: 3
Explanation: Each of the patterns appears as a substring in word "ab".

Constraints:

1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100

patterns[i] and word consist of lowercase English letters.

Looking through the problem description you understand that any pattern that is contained into the word its a match, so using contains method from String would do the trick.

A creation of a integer to count, iterating the array and comparing each if contains on the word would do the trick:

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

for(int i=0;i<patterns.length;i++){
if(word.contains(patterns[i])) count++;
}

return count;
}
}
``````

Runtime: 0 ms, faster than 100.00% of Java online submissions for Number of Strings That Appear as Substrings in Word.
Memory Usage: 40.9 MB, less than 57.71% of Java online submissions for Number of Strings That Appear as Substrings in Word.

You can also get it done one liner using Stream, is not the best performance wise but still good enough:

``````class Solution {
public int numOfStrings(String[] patterns, String word) {
return (int) Stream.of(patterns).filter(p -> word.contains(p)).count();
}
}
``````

Runtime: 2 ms, faster than 7.50% of Java online submissions for Number of Strings That Appear as Substrings in Word.
Memory Usage: 41.6 MB, less than 5.81% of Java online submissions for Number of Strings That Appear as Substrings in Word.

As you can see from runtime and memory usage its little bit heavier, so if performance might be an issue, focus on simple approach instead of using a lot of different processes.

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)