1. 程式人生 > >267. Palindrome Permutation II

267. Palindrome Permutation II

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

Example 1:

Input: "aabb"
Output: ["abba", "baab"]
Example 2:

Input: "abc"
Output: []



Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if
no palindromic permutation could be form. Example 1: Input: "aabb" Output: ["abba", "baab"] Example 2: Input: "abc" Output: [] https://leetcode.com/problems/palindrome-permutation-ii/description/ class Solution { public List<String> generatePalindromes(String s) { int odd = 0; String mid
= ""; List<String> res = new ArrayList<>(); List<Character> list = new ArrayList<>(); Map<Character, Integer> map = new HashMap<>(); // build freq map from string for(int i = 0; i < s.length(); i++){
char c = s.charAt(i); if(!map.containsKey(c)){ map.put(c, 1); }else{ map.put(c, map.get(c) + 1); } odd += map.get(c) % 2 == 0 ? -1 : 1; } // check if can form a palindrom if(odd > 1) return res; // add half freq of chars to a list for(Map.Entry<Character, Integer> entry : map.entrySet()){ char key = entry.getKey(); int val = entry.getValue(); if(val % 2 != 0) mid += key; for(int i = 0; i < val / 2; i++) list.add(key); } // permutation on the first half, reverse it , becomes the second half , // add mid if necessary boolean[] used = new boolean[list.size()]; StringBuilder sb = new StringBuilder(); permutation(res, list, mid, used, sb); return res; } private void permutation(List<String> res, List<Character> list, String mid, boolean[] used, StringBuilder sb){ // base case if(sb.length() == list.size()){ res.add(sb.toString() + mid + sb.reverse().toString()); sb.reverse(); // ? return; } for(int i = 0; i < list.size(); i++){ // avoid duplication // aaaaabbbbc if(i > 0 && list.get(i) == list.get(i - 1) && !used[i - 1]) continue; if(!used[i]){ used[i] = true; sb.append(list.get(i)); permutation(res, list, mid, used, sb); // backtracking used[i] = false; sb.deleteCharAt(sb.length() - 1); } } } } Input: "aabbcc" Output: ["abccba","ccbbcc","baccab","ccaacc","cabbac","bbaabb"] Expected: ["abccba","acbbca","baccab","bcaacb","cabbac","cbaabc"]