LeetCode-Palindrome Permutation II
2016-08-29 14:02
337 查看
Given a string
For example:
Given
Given
Analysis:
Should ask if the chars contains only letters, lowercase letters or any char.
Solution:
s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
For example:
Given
s = "aabb", return
["abba", "baab"].
Given
s = "abc", return
[].
Analysis:
Should ask if the chars contains only letters, lowercase letters or any char.
Solution:
import java.util.Map.Entry; public class Solution { public List<String> generatePalindromes(String s) { List<String> resList = new ArrayList<String>(); if (s.isEmpty()) return resList; HashMap<Character, Integer> charMap = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); i++) { char curChar = s.charAt(i); int count = charMap.getOrDefault(curChar, 0); charMap.put(curChar, count + 1); } int[] counts = new int[charMap.size()]; char[] chars = new char[charMap.size()]; int ind = 0; for (Entry entry : charMap.entrySet()) { chars[ind] = (char) entry.getKey(); counts[ind++] = (int) entry.getValue(); } // If there is more than one odd count, fail. boolean hasOdd = false; int oddIndex = -1; for (int i = 0; i < counts.length; i++) if (counts[i] % 2 == 1) { if (hasOdd) return resList; hasOdd = true; oddIndex = i; } StringBuilder builder = new StringBuilder(); int leftLen = s.length(); if (hasOdd) { char c = chars[oddIndex]; counts[oddIndex]--; builder.append(c); leftLen--; } getPalindromes(chars, counts, leftLen, builder, resList); return resList; } public void getPalindromes(char[] chars, int[] counts, int leftLen, StringBuilder builder, List<String> resList) { if (leftLen == 0) { resList.add(builder.toString()); return; } for (int i = 0; i < counts.length; i++) if (counts[i] > 0) { char curChar = chars[i]; counts[i] -= 2; builder.insert(0, curChar); builder.append(curChar); getPalindromes(chars, counts, leftLen - 2, builder, resList); builder.deleteCharAt(builder.length() - 1); builder.deleteCharAt(0); counts[i] += 2; } } }
相关文章推荐
- [LeetCode]Palindrome Permutation II
- [LeetCode 267] Palindrome Permutation II
- [LeetCode] Palindrome Permutation I & II
- Leetcode: Palindrome Permutation II
- LeetCode Palindrome Permutation II
- [LeetCode] Palindrome Permutation II
- [LeetCode267]Palindrome Permutation II
- [LeetCode] Palindrome Permutation II 回文全排列之二
- Leetcode Palindrome Permutation I & II
- leetcode - Palindrome Partitioning II
- leetcode 680 Valid Palindrome II
- leetcode第一刷_ Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II, Solution
- Leetcode: Palindrome Partitioning II
- Permutation II @leetcode
- [Leetcode] Palindrome Partitioning II (Java)
- leetcode Palindrome Partitioning II
- leetcode || 132、Palindrome Partitioning II
- Palindrome Permutation II
- leetcode — palindrome-partitioning-ii