【问题标题】:Big-O of One Word Anagram一个单词字谜的大 O
【发布时间】:2014-01-20 18:50:25
【问题描述】:

我创建了一个程序,它接受一个字符串,例如“计算机”,并输出所有可以由它组成的字典单词。但是我很难弄清楚程序的 Big-O 效率是什么,因为它使用递归和 binarySearch。

另外,程序可以变得更有效率吗?我还没有研究过哈希图或其他数据结构。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class WordScramble {

    static String[] dictArr;
    static int index;

    // print permutation / combination of the characters of the string s (in order)
    public static void permWord(String s) { permWord("", s); }

    private static void permWord(String prefix, String s) {
        int n = s.length();
        if (n != 0){
            for (int i = 0; i < n; i++)
               permWord(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
        }
        index = Arrays.binarySearch(dictArr, prefix);
        if (index > 0)
            System.out.println(prefix);
    }
    public static ArrayList<String> getLines(File f) throws FileNotFoundException { 
        ArrayList<String> dict = new ArrayList<String>();
        Scanner scan = new Scanner(f);
        while (scan.hasNext()){
            dict.add(scan.next());
        }
        scan.close();
        return dict;
    }
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("wordlist.txt");
        ArrayList<String> dictionary = getLines(f);
        dictArr = new String[dictionary.size()];
        dictArr = dictionary.toArray(dictArr);
        permWord("computer");       
    }
}

【问题讨论】:

  • 只考虑逻辑而不是实现。长度为n 的字符串有多少种排列?对于其中的每一个,都有一个二进制搜索。答案是n! - 所以复杂度是n!ln(k),其中n 是单词的长度,k 是字典的大小。实际上,n! 的任何倍数都非常小,所以这里的大问题是 n 的大小而不是字典的大小。
  • @BoristheSpider 这可能是一个答案......
  • 这个问题在 codereview.stackexchange.com 上可能会做得更好,尤其是您询问是否可以提高效率的部分。
  • 感谢 Boris 理解复杂性

标签: java algorithm recursion big-o binary-search


【解决方案1】:

更好的方法是扫描字典并检查哪些单词是原始单词的字谜。

您可以通过匹配原始单词中每个字母的计数来进行此检查。

复杂度 O(k) 其中 k 是字典中所有单词的字母总数。

此链接显示了解决此类问题的更多方法。 Best algorithm to find anagram of word from dictonary

【讨论】:

  • 我喜欢这个。当输入词的大小大于9时,我的原始方法失败了,搜索次数为9!或 362880,它是我的单词列表大小的两倍,而且对于更长的单词,它只会成倍恶化。
猜你喜欢
  • 2016-02-01
  • 2020-09-25
  • 2011-02-07
  • 2021-08-27
  • 2013-12-29
  • 2017-12-02
  • 2020-09-26
  • 2014-09-03
  • 2012-09-10
相关资源
最近更新 更多