栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java词典搜索器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java词典搜索器

如果要支持20个或更多的字符,以各种可能的方式拆分输入字符串将不会在合理的时间内完成。内联评论:这是一种更有效的方法:

public static void main(String[] args) throws IOException {    // load the dictionary into a set for fast lookups    Set<String> dictionary = new HashSet<String>();    Scanner filescan = new Scanner(new File("dictionary.txt"));    while (filescan.hasNext()) {        dictionary.add(filescan.nextLine().toLowerCase());    }    // scan for input    Scanner scan = new Scanner(System.in);    System.out.print("Enter a string: ");    String input = scan.next().toLowerCase();    System.out.println();    // place to store list of results, each result is a list of strings    List<List<String>> results = new ArrayList<>();    long time = System.currentTimeMillis();    // start the search, pass empty stack to represent words found so far    search(input, dictionary, new Stack<String>(), results);    time = System.currentTimeMillis() - time;    // list the results found    for (List<String> result : results) {        for (String word : result) { System.out.print(word + " ");        }        System.out.println("(" + result.size() + " words)");    }    System.out.println();    System.out.println("Took " + time + "ms");}public static void search(String input, Set<String> dictionary,        Stack<String> words, List<List<String>> results) {    for (int i = 0; i < input.length(); i++) {        // take the first i characters of the input and see if it is a word        String substring = input.substring(0, i + 1);        if (dictionary.contains(substring)) { // the beginning of the input matches a word, store on stack words.push(substring); if (i == input.length() - 1) {     // there's no input left, copy the words stack to results     results.add(new ArrayList<String>(words)); } else {     // there's more input left, search the remaining part     search(input.substring(i + 1), dictionary, words, results); } // pop the matched word back off so we can move onto the next i words.pop();        }    }}

输出示例:

Enter a string: amana man (2 words)am an (2 words)Took 0ms

这是更长的输入:

Enter a string: thequickbrownfoxjumpedoverthelazydogthe quick brown fox jump ed over the lazy dog (10 words)the quick brown fox jump ed overt he lazy dog (10 words)the quick brown fox jumped over the lazy dog (9 words)the quick brown fox jumped overt he lazy dog (9 words)Took 1ms


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451351.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号