LeetCode-in-Java

3093. Longest Common Suffix Queries

Hard

You are given two arrays of strings wordsContainer and wordsQuery.

For each wordsQuery[i], you need to find a string from wordsContainer that has the longest common suffix with wordsQuery[i]. If there are two or more strings in wordsContainer that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer.

Return an array of integers ans, where ans[i] is the index of the string in wordsContainer that has the longest common suffix with wordsQuery[i].

Example 1:

Input: wordsContainer = [“abcd”,”bcd”,”xbcd”], wordsQuery = [“cd”,”bcd”,”xyz”]

Output: [1,1,1]

Explanation:

Let’s look at each wordsQuery[i] separately:

Example 2:

Input: wordsContainer = [“abcdefgh”,”poiuygh”,”ghghgh”], wordsQuery = [“gh”,”acbfgh”,”acbfegh”]

Output: [2,0,2]

Explanation:

Let’s look at each wordsQuery[i] separately:

Constraints:

Solution

public class Solution {
    public int[] stringIndices(String[] wc, String[] wq) {
        int minLength = wc[0].length();
        int minIndex = 0;
        int n = wc.length;
        int m = wq.length;
        for (int i = 0; i < n; i++) {
            if (minLength > wc[i].length()) {
                minLength = wc[i].length();
                minIndex = i;
            }
        }
        Trie root = new Trie(minIndex);
        for (int i = 0; i < n; i++) {
            Trie curr = root;
            for (int j = wc[i].length() - 1; j >= 0; j--) {
                char ch = wc[i].charAt(j);
                if (curr.has(ch)) {
                    Trie next = curr.get(ch);
                    if (wc[next.index].length() > wc[i].length()) {
                        next.index = i;
                    }
                    curr = next;
                } else {
                    curr.put(ch, i);
                    curr = curr.get(ch);
                }
            }
        }
        int[] ans = new int[m];
        for (int i = 0; i < m; i++) {
            Trie curr = root;
            for (int j = wq[i].length() - 1; j >= 0; j--) {
                char ch = wq[i].charAt(j);
                if (curr.has(ch)) {
                    curr = curr.get(ch);
                } else {
                    break;
                }
            }
            ans[i] = curr.index;
        }

        return ans;
    }

    private static class Trie {
        Trie[] ch;
        int index;

        Trie(int index) {
            this.ch = new Trie[26];
            this.index = index;
        }

        Trie get(char ch) {
            return this.ch[ch - 'a'];
        }

        boolean has(char ch) {
            return this.ch[ch - 'a'] != null;
        }

        void put(char ch, int index) {
            this.ch[ch - 'a'] = new Trie(index);
        }
    }
}