使用java中的索引交换数字不起作用

package dspermutation; import java.util.Scanner; public class DSPermutation { String s; char[] c; int n; public static void main(String[] args) { DSPermutation ds=new DSPermutation(); ds.input(); } private void input() { Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); s=sc.next(); c=s.toCharArray(); n=c.length; permutation(c,n-1,0); } private void permutation(char[] cc,int nn,int ii) { if(ii==nn) { System.out.println(cc); } else { for(int j=ii;j<=nn;j++) { swap(cc[ii],cc[j]); permutation(cc,nn,ii+1); swap(cc[ii],cc[j]); } } } private void swap(char p, char c0) { int x=s.indexOf(p); int y=s.indexOf(c0); /*1*/ char temp=c[x]; /*2*/c[x]=c[y]; /*3*/c[y]=temp; /*c[x]=c0; c[y]=p;*/ } } 

上面的程序用于打印给定字符串的所有排列结果。但是在swap()方法中,如果我用注释中写入的逻辑替换第1,2,3行(在注释中写入)(第1,2行之后) 3)然后回答错误。 为什么会发生这种情况?

你的错误是假设c[x] == pc[y] == c0 。 但索引xy是从不可变字符串s派生s ,它不反映其洗牌状态下c中的值。

您正在使用immutable字符串的位置交换字符数组的值(即字符串始终保持相同的初始值)。 要使您的注释代码工作,您必须添加此s = String.valueOf(c);swapfunction结束时。

 private void swap(char p, char c0) { int x = s.indexOf(p); int y = s.indexOf(c0); // char temp = c[x]; // c[x] = c[y]; // c[y] = temp; c[y] = p; c[x] = c0; s = String.valueOf(c); }