Input: words =["mass","as","hero","superhero"]Output: ["as","hero"]Explanation: "as"is substring of "mass" and "hero"is substring of "superhero".["hero","as"]is also a valid answer.
classSolution {
public List<String>stringMatching(String[] words) {
List<String> ans =new ArrayList<>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words.length; j++) {
if (i != j && words[j].contains(words[i])) {
ans.add(words[i]);
break;
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defstringMatching(self, words: List[str]) -> List[str]:
ans: List[str] = []
for i in range(len(words)):
for j in range(len(words)):
if i != j and words[i] in words[j]:
ans.append(words[i])
breakreturn ans
⏰ Time complexity: O(n^2 * l^2) where n is the number of words and l is the average length of a word in words. Because we run 2 loops to match the words and then contains method takes O(l1*l2) and assuming average length of words is l, it becomes O(l^2).
🧺 Space complexity: O(n) for storing the result list.