Created
June 8, 2014 01:43
-
-
Save lamchau/3cc46e074e8bbc8ee28a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.lchau; | |
public class Permutations { | |
public static void main(String[] args) { | |
String str = "Hello, world"; | |
Permutations.permute(0, str.length() - 1, str.toCharArray()); | |
} | |
private static boolean match(int i, int j, char[] chars) { | |
if (i != j) { | |
for (; i < j; i++) { | |
if (chars[i] == chars[j]) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
private static void permute(int index, int length, char[] str) { | |
if (index == length) { | |
System.out.println(new String(str)); | |
return; | |
} | |
for (int i = index; i <= length; i++) { | |
if (Permutations.match(index, i, str)) { | |
continue; | |
} | |
Permutations.swap(index, i, str); | |
Permutations.permute(index + 1, length, str); | |
Permutations.swap(index, i, str); | |
} | |
} | |
private static void swap(int i, int j, char[] str) { | |
char temp = str[i]; | |
str[i] = str[j]; | |
str[j] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment