使用Java生成所有单词 [英] Generate all words using Java

查看:109
本文介绍了使用Java生成所有单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用指定字符和长度的java生成所有单词

I want to know how to generate all words using java from specified characters and length

String first[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String second[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String ch ="";  
String total[];

for(int i = 0;i<26;i++) {
    for(int j = 0;j<26;j++) {
        ch+=first[i]+first[j];
        System.out.println(ch);
    }
}

我只得到这个程序的576字,但是26!单词是4.03291461×10 ^ 26

I get only 576 words only by this program, but the 26! words is 4.03291461 × 10^26

如何用java编写程序?

How to write the program in java?

推荐答案

这是我的解决方案。这有点快,所以不要太过于优化。

Here's my solution. It's kind of quick, so don't be too hard on the optimization.

public static void printWords(int length) {

    if (length < 1)
        throw new IllegalArgumentException();

    printWordsRec("", length);
}

private static void printWordsRec(String base, int length) {

    for (char c = 'a'; c <= 'z'; c++) {
        if (length == 1) {
            System.out.println(base + c);
        }
        else {
            printWordsRec(base + c, length - 1);
        }
    }
}

这篇关于使用Java生成所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆