LeetCode 1408: String Matching in an Array Solution
Master LeetCode problem 1408 (String Matching in an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1408. String Matching in an Array
Problem Explanation
Explanation
To solve this problem, we iterate through each pair of words and check if one word is a substring of another. We can accomplish this by using two nested loops to compare each pair of words. For each pair, we check if one word is a substring of the other using the indexOf method in Java and Python, and the find method in C++. If a word is found to be a substring of another, we add it to the result set. Finally, we return the result set as the output.
- Time Complexity: O(n^2 * m), where n is the number of words in the input array and m is the average length of the words.
- Space Complexity: O(1) if we don't consider the space for the output list.
Solution Code
import java.util.*;
class Solution {
public List<String> stringMatching(String[] words) {
List<String> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words.length; j++) {
if (i != j && words[j].indexOf(words[i]) != -1) {
result.add(words[i]);
break;
}
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1408 (String Matching in an Array)?
This page provides optimized solutions for LeetCode problem 1408 (String Matching in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1408 (String Matching in an Array)?
The time complexity for LeetCode 1408 (String Matching in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1408 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1408 in Java, C++, or Python.