【发布时间】: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