题目描述
回文字符串是指一个字符串从左往右读和从右往左读是相同的,例如:abcba,aba等。
现在小图灵得到了T个仅包含小写字母的字符串,他想知道对于每个字符串来说,能否重新组合得到K个回文字符串。请你帮助他解决
问题。
输入描述
第1行包括一个整数工,代表字符串的个数。
第2~T+1行包含一个仅含有小写字母的字符串,每个字符串的长度都不超过n。
输出描述
输出共T行,对于每个字符串来说,结果输出在一行上。若重组得到回文字符串有K个,当K=1时,输出onlyone,当K=2时,
输出 only two;当K>2时,输出more;若不能得到回文字符串则输出 no。
一开始是想着求计数个字母的个数,但是不对
```c++
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
bool canFormPalindromes(string str) {
unordered_map<char, int> count;
for (char c : str) {
count[c]++;
}
int oddCount = 0;
for (auto entry : count) {
if (entry.second % 2 != 0) {
oddCount++;
}
}
return oddCount <= 1;
}
string getPalindromeCount(string str) {
if (canFormPalindromes(str)) {
unordered_map<char, int> count;
for (char c : str) {
count[c]++;
}
int distinctChars = count.size();
if (distinctChars == 1) {
return "only one";
} else if (distinctChars == 2) {
return "only two";
} else {
return "more";
}
} else {
return "no";
}
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
string str;
cin >> str;
cout << getPalindromeCount(str) << endl;
}
return 0;
}
还有这一版
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool canFormPalindromes(string str) {
vector<int> count(26, 0);
int oddCount = 0;
for (char c : str) {
count[c - 'a']++;
}
for (int freq : count) {
if (freq % 2 != 0) {
oddCount++;
}
}
return oddCount <= 1;
}
string getPalindromeCount(string str) {
if (canFormPalindromes(str)) {
int distinctChars = count_if(str.begin(), str.end(), [&](char c) {
return count(str.begin(), str.end(), c) % 2 != 0;
});
if (distinctChars == 1 || distinctChars == 2) {
return "only two";
} else {
return "more";
}
} else {
return "no";
}
}
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
string str;
cin >> str;
cout << getPalindromeCount(str) << endl;
}
return 0;
}
```