Leetcode 1408. String Matching in an Array
Given an array of string words
, return all strings in words
that are a substring of another word in any order. A string words[i]
is a substring of words[j]
, if i != j
and words[i]
is a substring of words[j]
.
Example:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
words
and individual strings should be reasonable to fit into memory.words
contain duplicate strings?
words
can contain duplicates.substrings
to store unique substrings.import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class StringMatchingInAnArray {
public List<String> stringMatching(String[] words) {
// Initialize a HashSet to keep track of unique substrings
HashSet<String> substrings = new HashSet<>();
// Length of the words array
int n = words.length;
// Loop through each pair of words in the array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && words[j].contains(words[i])) {
substrings.add(words[i]);
}
}
}
// Convert the set to a list and return it
return new ArrayList<>(substrings);
}
public static void main(String[] args) {
StringMatchingInAnArray solution = new StringMatchingInAnArray();
String[] words1 = {"mass","as","hero","superhero"};
System.out.println(solution.stringMatching(words1)); // Output: [as, hero]
String[] words2 = {"leetcode","et","code"};
System.out.println(solution.stringMatching(words2)); // Output: [et, code]
}
}
contains()
method runs in (O(m)).n
substrings in the HashSet and the final list.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?