使用Java生成所有单词(Generate all words using Java)

编程入门 行业动态 更新时间:2024-10-23 13:37:13
使用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); } } }

更多推荐

本文发布于:2023-07-31 21:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   Java   words   Generate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!