Given a dictionary and a list of letters find all valid words that can be built with the letters

前端 未结 12 1061
闹比i
闹比i 2021-01-31 12:26

The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the com

12条回答
  •  萌比男神i
    2021-01-31 12:45

    Assume that letters only contains letters from a to z.

    Use an integer array to count the number of occurrence of a character in letters.

    For each word in the dictionary, check if there is a specific character in the word that appears more than allowed, if not, add this word into result.

        List findValidWords(List dict, char letters[]){
            int []avail = new int[26];
            for(char c : letters){
                int index = c - 'a';
                avail[index]++;
            }
            List result = new ArrayList();
            for(String word: dict){
                int []count = new int[26];
                boolean ok = true;
                for(char c : word.toCharArray()){
                    int index = c - 'a';
                    count[index]++;
                    if(count[index] > avail[index]){
                        ok = false;
                        break;
                    }
                }
                if(ok){
                    result.add(word);
                }
            }
            return result;
        }
    

    So we can see that the time complexity is O(m*k) with m is number of word in the dictionary and k is the maximum total of characters in a word

提交回复
热议问题