使用Java生成所有单词(Generate all words using Java)
我想知道如何使用指定字符和长度的java生成所有单词
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
如何在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); } }I get only 576 words only by this program, but the 26! words is 4.03291461 × 10^26
How to write the program in java?
最满意答案
这是我的解决方案。 这有点快,所以不要太苛求优化。
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); } } }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); } } }更多推荐
发布评论