Created
September 14, 2017 00:36
-
-
Save cixuuz/0976468eb880fd041af174c9419bca06 to your computer and use it in GitHub Desktop.
[267. Palindrome Permutation II] #leetcode
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
class Solution { | |
private List<String> list = new ArrayList<>(); | |
public List<String> generatePalindromes(String s) { | |
int numOdds = 0; // How many characters that have odd number of count | |
int[] map = new int[256]; // Map from character to its frequency | |
for (char c: s.toCharArray()) { | |
map[c]++; | |
numOdds = (map[c] & 1) == 1 ? numOdds+1 : numOdds-1; | |
} | |
if (numOdds > 1) return list; | |
String mid = ""; | |
int length = 0; | |
for (int i = 0; i < 256; i++) { | |
if (map[i] > 0) { | |
if ((map[i] & 1) == 1) { // Char with odd count will be in the middle | |
mid = "" + (char)i; | |
map[i]--; | |
} | |
map[i] /= 2; // Cut in half since we only generate half string | |
length += map[i]; // The length of half string | |
} | |
} | |
generatePalindromesHelper(map, length, "", mid); | |
return list; | |
} | |
private void generatePalindromesHelper(int[] map, int length, String s, String mid) { | |
if (s.length() == length) { | |
StringBuilder reverse = new StringBuilder(s).reverse(); // Second half | |
list.add(s + mid + reverse); | |
return; | |
} | |
for (int i = 0; i < 256; i++) { // backtracking just like permutation | |
if (map[i] > 0) { | |
map[i]--; | |
generatePalindromesHelper(map, length, s + (char)i, mid); | |
map[i]++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment