繁体   English   中英

如何对文本文件进行排序以在 O(MN) 时间复杂度中找到字谜,其中 M 是最大字符数,N 是单词数?

[英]How to sort a text file to find anagrams in O(MN) time complexity where M is the max number of characters and N is the number of words?

嗨,我是 Python 新手,我想在线性时间内在文件中找到多组字谜。字谜基本上是两个或多个单词,它们由相同的字母表组成,但排列方式不同。

首先,我将所有单词读入列表。 显然,我可以使用基数排序按列对每个单词进行排序,基数排序应该使用稳定的计数排序。 但我不知道我的计数排序应该做什么? 我应该编写一个计数排序函数来接收一个单词并按字母顺序对其进行排序吗? 然后以基数排序调用它?

有人可以让我更清楚地了解如何解决这个问题吗?任何帮助将不胜感激,谢谢!

希望这对你有帮助。 它也是 O(mn)

public List<List<String>> groupAnagrams(String[] strs){
    List<List<String>> result = new ArrayList<List<String>>();
    
    HashMap<ArrayList<Integer>, ArrayList<String>> map = new HashMap<ArrayList<Integer>, HashMap<ArrayList<String>>;
    
    for(String str : strs){
        ArrayList<Integer> arr = new ArrayList<Integer>();
        for(int i=0; i<str.length(); i++){
            arr[str.charAt(i)- 'a']++;
        }
        
        if(map.containsKey(arr)){
            map.get(arr).add(str);
        } else {
            ArrayList<String> al = new ArrayList<String>();
            al.add(str);
            map.put(arr, al);
        }
    }
    
    result.addAll(map.values());
    
    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM