分享一下上午做出来的两种方法:(时间太快,没写注释)
1.用递归做的:public class StringSort3 {
public static int count=0;
public static void main(String[] args){
String str="123456789";
sort("",str,7);
System.out.println(count);
}
public static void sort(String strPre,String str,int value){
if(value==0)
return;
String temp="";
String strL="";
for(int x=0;x<=str.length()-value;x++){
temp=strPre;
strPre=strPre+str.substring(x,x+1);
if(value==1){
System.out.println(strPre);
count++;
}
strL=str.substring(x+1,str.length());
value-=1;
sort(strPre,strL,value);
value+=1;
strPre=temp;
}
}
}
第二种方法:数组加循环
- public class StringSort2 {
- /**
- * @param args
- */
- public static int count=0;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str="0123456789";
- sort(str,4);
- System.out.println(count);
- }
-
- public static void sort(String str,int value){
- int pos1=0,pos2=0;
- char[] ch= str.toCharArray();
- char[] temp=new char[value];
- for(int x=0;x<temp.length;x++)
- temp[x]=ch[x];
- System.out.println(String.valueOf(temp));
- count++;
- for(int i=value;i<=ch.length;i++){
- if(i<ch.length){
- temp[value-1]=ch[i];
- System.out.println(String.valueOf(temp));
- count++;
- }
- else
- i=ch.length-1;
- if(i==ch.length-1){
- for(int a=1;a<=value;a++){
- if(temp[value-a]!=ch[ch.length-a]){
- pos1=a;
- break;
- }
- }
- for(int b=0;b<ch.length;b++){
- if(temp[value-pos1]==ch[b]){
- pos2=b;
- break;
- }
- }
- for(int a=pos1,b=pos2;a>0;a--,b++){
- temp[value-a]=ch[b+1];
- }
- System.out.println(String.valueOf(temp));
- count++;
- if(temp[0]==ch[ch.length-value])
- return;
- i=pos1+pos2;
- }
- }
- }
复制代码
|