Created
October 31, 2014 09:27
-
-
Save anupamkumar/5935e9719e119902ef7e to your computer and use it in GitHub Desktop.
Permutation of String - Iterative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
/** | |
* all permutations of a string / char array | |
* @author anupam | |
*/ | |
public class Problem6 { | |
public static ArrayList<String> allPerms(String str) { | |
ArrayList<String> al = new ArrayList<>(); | |
int i=0; | |
al.add(str); | |
while(i < al.size()) { | |
for(int j=0;j<al.get(i).length()-1;j++) { | |
String temp = swap(al.get(i),j,j+1); | |
if(exists(al,temp)) | |
continue; | |
else | |
al.add(temp); | |
} | |
i++; | |
} | |
return al; | |
} | |
private static String swap(String s, int i, int j) { | |
char[] ch = s.toCharArray(); | |
char temp = ch[i]; | |
ch[i] = ch[j]; | |
ch[j] = temp; | |
return new String(ch); | |
} | |
private static boolean exists(ArrayList<String> a, String s) { | |
for(String a1 : a) { | |
if(s.equals(a1)) | |
return true; | |
} | |
return false; | |
} | |
public static void main(String[] args) { | |
ArrayList<String> perms = allPerms("123"); | |
for(String s : perms) { | |
System.out.println(s); | |
} | |
System.out.println("Perm Count:"+perms.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment