标签:
递归做法
public class Solution { List<String> result = new ArrayList<String>(); public List<String> generatePalindromes(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); i++) { int tmp = map.containsKey(s.charAt(i)) ? map.get(s.charAt(i)) : 0; map.put(s.charAt(i), tmp + 1); } Iterator<Character> it = map.keySet().iterator(); char singal = ‘0‘; while (it.hasNext()) { char tmp = it.next(); if (map.get(tmp) % 2 != 0) { if (singal != ‘0‘) { return result; } singal = tmp; } } if (singal == ‘0‘) { helper(map, ""); } else { map.put(singal, map.get(singal) - 1); helper(map, String.valueOf(singal)); } return result; } public void helper(HashMap<Character, Integer> map, String str) { Iterator<Character> it = map.keySet().iterator(); boolean flg = true; while (it.hasNext()) { char tmp = it.next(); int count = map.get(tmp); if (count == 0) { continue; } flg = false; if (str.length() > 1 && tmp == str.charAt(0)) { continue; } for (int i = 0; i < count / 2; i++) { HashMap<Character, Integer> new_map = new HashMap<Character, Integer>(map); new_map.put(tmp, new_map.get(tmp) - (i + 1) * 2); String s = ""; for (int j = 0; j < i + 1; j++) { s += tmp; } helper(new_map, s + str + s); } } if (flg) { result.add(str); } } }
[LeetCode]Palindrome Permutation II
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5006209.html