String Matching in an Array
You are given an array of strings words
, and you need to find all the strings that are substrings of another string in the same array.
Approach
- Iterate through the
words
array. - For each word, check if it is a substring of any other word in the array.
- If a word is a substring of another word, add it to the result list.
- Return the result list.
Here’s the code:
|
|
Example
Let’s take words = ["mass","as","hero","superhero"]
as an example:
"as"
is a substring of"mass"
, so add it to the result."hero"
is a substring of"superhero"
, so add it to the result.
So the output will be ["as","hero"]
.
This solution checks each word against all other words, resulting in a time complexity of O(n^2 * m), where n is the number of words, and m is the maximum length of a word. This is acceptable for the given constraints.