← All problems

1408. String Matching in an Array

EasyOpen on LeetCodeProblem statement

Problem Statement

1408. String Matching in an Array

Easy


Given an array of string words, return all strings in words that is a substring of another word. You can return the answer in any order.

A substring is a contiguous sequence of characters within a string

 

Example 1:

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.

Example 2:

Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

Example 3:

Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.

 

Constraints:

Java

Source file

class Solution {
    private class TrieNode {
        int freq = 0;
        TrieNode[] children = new TrieNode[26];
    }
    private class Trie{
        TrieNode root;
        Trie(){
            root = new TrieNode();
        }

        public void insertWord(char[] word, int startIdx){
            TrieNode curr = root;
            for(int i=startIdx; i<word.length; i++){
                int c = word[i] - 'a';
                if(curr.children[c]==null)
                    curr.children[c] = new TrieNode();
                curr = curr.children[c];
                curr.freq += 1;
            }
        }

        public boolean countOccurances(String word){
            TrieNode curr = root;
            for(char x: word.toCharArray()){
                int c = x - 'a';
                if(curr.children[c]==null)
                    return false;
                curr = curr.children[c];
            }
            return curr.freq > 1;
        }

    }
    public List<String> stringMatching(String[] words) {
        Trie trie = new Trie();
        for(String w: words){
            char[] cs = w.toCharArray();
            for(int i=0; i<cs.length; i++)
                trie.insertWord(cs, i);
        }
        List<String> ans = new ArrayList<>();
        for(String w: words)
            if(trie.countOccurances(w))
                ans.add(w);
        return ans;
    }
}