您的位置:首页 > 其它

LeetCode-Palindrome Permutation II

2016-08-29 14:02 337 查看
Given a string
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: