打印置换字符串的问题
给出字符串(abc)希望实现:abc,acb,bac,bca,cab,cba的输出,程序如下:
import java.lang.*;
public class P412
{
public static void prt(int n,String str)
{
if (n<1)
{ return;
}
else if (n==1)
{
System.out.println(str);
}
else
{
for(int i=0;i<n;i++){
char tmpc=str.charAt(i);
String lft;
String rght;
if (i>0)
lft=str.substring(0,i-1);
else
lft="";
if(i<n)
rght=str.substring(i+1,n-1);
else
rght="";
String tmps=lft+rght;
System.out.print(tmpc);
prt(n-1,tmps);
}
}
}
public static void main(String[] args)
{
prt(3,"abc");
//System.out.println("Hello World!");
}
}
编译通过,运行出错,提示:
ab
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 1
at java.lang.String.charAt(String.java:455)
at P412.prt(P412.java:17)
at P412.prt(P412.java:30)
at P412.main(P412.java:36)
请高手指点,谢谢