牛客网诡异的判题系统
字符串的排列
http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
代码
import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; public class Solution { public ArrayList<String> Permutation(String str){ if (str==null||str.length()==0){ return new ArrayList<>(); }else { HashSet<String> set=new HashSet<>(); String newstr=""; PermutationHelper(set,newstr,str); ArrayList<String> arrayList=new ArrayList<>(); Iterator<String> iterator=set.iterator(); while (iterator.hasNext()){ arrayList.add(iterator.next()); } return arrayList; } } public void PermutationHelper(HashSet<String> set, String newstr, String str){ if (str.length()==1){ newstr=newstr+str; set.add(newstr); return; } for (int i=0;i<str.length();i++){ String s= str.charAt(i)+""; String str1 = ""; String str2 = ""; if (i-1>-1&&i+1<str.length()){ str1=str.substring(0,i); str2=str.substring(i+1,str.length()); }else if (i-1<0){ str1=str.substring(1,str.length()); }else if (i+1>=str.length()){ str1=str.substring(0,str.length()-1); } PermutationHelper(set,newstr+s,str1+str2); } } }