java-查找单词中的字母子集
我试图找出单词中字母子集的字谜;例如,如果单词是“hello”,程序将检查整个单词,然后检查缺少1个字母的单词,依此类推 这是我的代码,我不确定哪里做错了:java-查找单词中的字母子集,java,string,permutation,subset,anagram,Java,String,Permutation,Subset,Anagram,我试图找出单词中字母子集的字谜;例如,如果单词是“hello”,程序将检查整个单词,然后检查缺少1个字母的单词,依此类推 这是我的代码,我不确定哪里做错了: import java.util.*; import java.io.*; class Perm { public static void main(String[] args) { System.out.println(permutations("hello")); } public stat
import java.util.*;
import java.io.*;
class Perm {
public static void main(String[] args) {
System.out.println(permutations("hello"));
}
public static String permutations(String word) {
String s = "";
for(int i=0; i<word.length(); i++) {
char ithChar = word.charAt(i);
String newWord = word.substring(0,i) + word.substring(i+1);
s = permutations(newWord);
}
return s;
}
}
import java.util.*;
导入java.io.*;
类烫发{
公共静态void main(字符串[]args){
System.out.println(排列(“hello”);
}
公共静态字符串置换(字符串字){
字符串s=“”;
对于(int i=0;i,因为我认为在方法中不需要这种误解。请尝试将其重写如下:
public static void permutations(String word) {
for(int i = word.length(); i > 0; i--){
System.out.println(word.substring(0, i));
}
}
public class Perm {
public static void main(String[] args) {
String word = "hello";
for(int i=word.length(); i!=0; i--) {
String permutation = word.substring(0, i);
System.out.println(permutation);
}
}
}
如果您不需要存储此文件,只需打印即可。
但正如您所猜测的,主要思想是使用递减循环。尝试以下方法:
public static void permutations(String word) {
for(int i = word.length(); i > 0; i--){
System.out.println(word.substring(0, i));
}
}
public class Perm {
public static void main(String[] args) {
String word = "hello";
for(int i=word.length(); i!=0; i--) {
String permutation = word.substring(0, i);
System.out.println(permutation);
}
}
}
每次循环运行时,它都会从单词的末尾去掉一个字符,您将得到如下输出:
hello
hell
hel
he
h
(也可以很容易地将其更改为去掉单词开头的字母)
我希望这就是您想要的,因为问题不是很清楚。(您可能还想看看。)请参阅如何正确获取Java中字符串的所有排列