[LeetCode] Palindrome Permutation II

267. Palindrome Permutation II

Given a string s, return all the palindromic permutations (without duplicates) of it.

You may return the answer in any order. If s has no palindromic permutation, return an empty list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
vector<string> res;
void helper(string& s, int l, int r, unordered_map<char,int>& counter) {
if(l == r) {
for(auto& [ch, c] : counter) {
if(c == 1) {
s[l] = ch;
res.push_back(s);
}
}
} else if(l > r) {
res.push_back(s);
} else {
for(auto& [ch, c] : counter) {
if(c >= 2) {
s[l] = s[r] = ch;
counter[ch] -= 2;
helper(s, l + 1, r - 1, counter);
counter[ch] += 2;
}
}
}
}
public:
vector<string> generatePalindromes(string s) {
unordered_map<char,int> counter;
for(auto& ch: s) counter[ch]++;
helper(s, 0, s.length() - 1, counter);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/13/PS/LeetCode/palindrome-permutation-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.