Problem Statement
|
|
You have some cards. Each card contains a single lowercase letter. You are given these letters as the characters of the string card.
A
palindrome is a string that reads the same forwards and backwards.
Examples of palindromes: "eve", "abba", "aaaaaa", and "racecar".
Use
the cards you have to spell some palindromes. In particular:
-
Each card must be used in exactly one of the palindromes.
-
The total number of palindromes must be as small as possible.
Return a vector <string> containing the palindromes you built. (Each
element of the return value should be one of the palindromes.)
A
solution always exists. If there are multiple optimal solutions, you
may choose and output any one of them.
|
Definition
|
|
Class:
|
MakePalindrome
|
Method:
|
constructMinimal
|
Parameters:
|
string
|
Returns:
|
vector <string>
|
Method signature:
|
vector <string> constructMinimal(string card)
|
(be sure your method is public)
|
|
Limits
|
|
Time limit (s):
|
2.000
|
Memory limit (MB):
|
256
|
Stack limit (MB):
|
256
|
|
Constraints
|
-
|
card will contain between 1 and 1,000 characters, inclusive.
|
-
|
Each character in card will be a lowercase English letter
(‘a‘-‘z‘).
|
Examples
|
0)
|
|
|
|
Returns: {"ababa" }
|
We can rearrange all letters into a single palindrome. There are two ways to do so: one is "ababa", the other is "baaab". |
|
|
1) |
|
|
|
Returns: {"a", "b", "c" }
|
This time the only solution is to build three palindromes, each consisting of a single letter. Note that you may return the three strings in any order. |
|
|
2) |
|
|
|
Returns: {"aba", "bcb", "cac" }
|
There are other solutions like {"aaa", "bbb", "ccc"} |
|
|
3) |
|
|
|
Returns: {"oco", "d", "e", "p", "r", "t" }
|
|
|
4) |
|
|
|
public class MakePalindrome
{
vector constructMinimal(string card) {
map<char, int> mp;
mp.clear();
vector ret;
ret.clear();
for(int i=0;i<card.size();i++) {
mp[card[i]] ++;
}
string f = "";
for(char i = ‘a‘; i <= ‘z‘; i++) {
// cout<<i<<" "<<mp[i]<<"\n";
if(mp[i] % 2 == 0) {
for(int j=0;j<mp[i]/2;j++) {
f.push_back(i);
}
mp[i] = 0;
}
}
bool flag = 0;
// Add character with odd occurrence
for(char i = ‘a‘; i <= ‘z‘; i++) {
if(mp[i]&1) {
flag = 1;
for(int j=0;j<mp[i]/2;j++) {
f.push_back(i);
}
string temp = f;
cout<<temp<<"\n";
reverse(temp.begin(), temp.end());
f = f + i + temp;
mp[i] = 0;
break;
}
}
// if all characters are of even occurrence
if(!flag){
string temp = f;
reverse(temp.begin(), temp.end());
f = f + temp;
ret.push_back(f);
return ret;
}
ret.push_back(f);
f = "";
// for all other characters of odd occurrence
for(char i = ‘a‘; i <= ‘z‘; i++) {
f = "";
// cout<<i<<" "<<mp[i]<<"\n";
if(mp[i]&1) {
for(int j=0;j<mp[i];j++) {
f.push_back(i);
}
ret.push_back(f);
}
}
return ret;
}
}