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

前端 未结 12 885
闹比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条回答
  •  太阳男子
    2021-01-31 12:33

    If letters can be repeated, that means that a word can be infinitely long. You would obviously cap this at the length of the longest word in the dictionary, but there are still too many words to check. Like nmore suggested, you'd rather iterate over the dictionary to do this.

    List findAllValidWords(Set dict, char[] letters) {
      List result = new LinkedList<>();
      Set charSet = new HashSet<>();
      for (char letter : letters) {
        charSet.add(letter);
      }
      for (String word : dict) {
        if (isPossible(word, charSet)) {
          result.add(word);
        }
      }
      return result;
    }
    
    boolean isPossible(String word, Set charSet) {
      // A word is possible if all its letters are contained in the given letter set
      for (int i = 0; i < word.length(); i++) {
        if (!charSet.contains(word.charAt(i))) {
          return false;
        }
      }
      return true;
    }
    

提交回复
热议问题