|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +/** |
| 9 | + * 1408. String Matching in an Array |
| 10 | + * |
| 11 | + * Given an array of string words. Return all strings in words which is substring of another word in any order. |
| 12 | + * String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j]. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * Input: words = ["mass","as","hero","superhero"] |
| 16 | + * Output: ["as","hero"] |
| 17 | + * Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". |
| 18 | + * ["hero","as"] is also a valid answer. |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * Input: words = ["leetcode","et","code"] |
| 22 | + * Output: ["et","code"] |
| 23 | + * Explanation: "et", "code" are substring of "leetcode". |
| 24 | + * |
| 25 | + * Example 3: |
| 26 | + * Input: words = ["blue","green","bu"] |
| 27 | + * Output: [] |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * 1 <= words.length <= 100 |
| 31 | + * 1 <= words[i].length <= 30 |
| 32 | + * words[i] contains only lowercase English letters. |
| 33 | + * It's guaranteed that words[i] will be unique. |
| 34 | + * */ |
| 35 | +public class _1408 { |
| 36 | + public static class Solution1 { |
| 37 | + public List<String> stringMatching(String[] words) { |
| 38 | + Set<String> set = new HashSet<>(); |
| 39 | + for (String word : words) { |
| 40 | + for (int i = 0; i < words.length; i++) { |
| 41 | + if (!word.equals(words[i]) && word.length() < words[i].length()) { |
| 42 | + if (words[i].indexOf(word) != -1) { |
| 43 | + set.add(word); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + List<String> result = new ArrayList<>(); |
| 49 | + for (String s : set) { |
| 50 | + result.add(s); |
| 51 | + } |
| 52 | + return result; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments