Find anagram of input on set of strings..?

后端 未结 3 1043
小鲜肉
小鲜肉 2021-02-10 13:59

Given a set of strings (large set), and an input string, you need to find all the anagrams of the input string efficiently. What data structure will you use. And using that, how

3条回答
  •  悲&欢浪女
    2021-02-10 14:33

    You could build an hashmap where the key is sorted(word), and the value is a list of all the words that, sorted, give the corresponding key:

    private Map> anagrams = new HashMap>();
    
    void buildIndex(){
        for(String word : words){
            String sortedWord = sortWord(word);
            if(!anagrams.containsKey(sortedWord)){
                anagrams.put(sortedWord, new ArrayList());
            }
            anagrams.get(sortedWord).add(word);
        }
    }
    

    Then you just do a lookup for the sorted word in the hashmap you just built, and you'll have the list of all the anagrams.

提交回复
热议问题