我在输出中得到一个错误,因为我需要在新的StringBuilder(";")来打印输出,而它应该是new StringBuilder(")我也试过一个在线编译器,它给出了同样的错误这是输入代码
public class Main
{
public static void main(String[] args)
{
String abc="appnacolllege";
Strchk(abc, 0, new StringBuilder(" "),new boolean[26]);
}
public static void Strchk (String abc,int i,StringBuilder str,boolean stroc[] )
{
if(i==str.length())
{System.out.println(str);
return;}
char currChar=abc.charAt(i);
if(stroc[currChar-'a']==true)
//duplicate
Strchk(abc, i+1, str, stroc);
else
{
stroc[currChar-'a']=true;
Strchk(abc, i+1, str.append(currChar), stroc);
}
}
}
Strchk
函数有一个小bug。碱条件应为i
=abc.length()
,而不是str.length()
。函数应该是这样的:
public static void Strchk (String abc, int i, StringBuilder str, boolean[] stroc)
{
if( i==abc.length() ) {
System.out.println(str);
return;
}
char currChar=abc.charAt(i);
if(stroc[currChar - 'a'])
//duplicate
Strchk(abc, i+1, str, stroc);
else
{
stroc[currChar-'a']=true;
Strchk(abc, i+1, str.append(currChar), stroc);
}
}
我重新编写了您的代码,并删除了对stroc
参数的要求。
这是你想要的流程吗?
只添加唯一字符。
void strchk(String string, int index, StringBuilder builder) {
if (index >= string.length()) {
System.out.println(builder);
return;
}
char character = string.charAt(index);
if (!builder.toString().contains(String.valueOf(character))) {
strchk(string, index + 1, builder.append(character));
} else {
strchk(string, index + 1, builder);
}
}
输出apncoleg