用C ++构造K回文字符串
假设我们有一个字符串s和一个数字k。我们必须使用s中的所有字符构造k个非空回文字符串。因此,在这里我们必须检查是否可以使用s中的所有字符来构造k个回文字符串。
因此,如果输入像“true”,k=4,则输出将为True,因为唯一可能的解决方案是将每个字符放在单独的字符串中。
为了解决这个问题,我们将遵循以下步骤-
n:=s的大小
如果n<k,则-
返回假
如果n与k相同,则-
返回真
定义一张映射
对于s中的每个字符c
(将m[c]增加1)
奇数:=0
对于每个键值对,以m为单位-
奇数:=奇数+(其值与1)
当奇数<=k时返回true,否则返回false
例
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool canConstruct(string s, int k) {
int n = s.size();
if (n < k)
return false;
if (n == k)
return true;
map<char, int> m;
for (char c : s)
m[c]++;
int odd = 0;
for (auto& it : m) {
odd += (it.second & 1);
}
return odd <= k;
}
};
main(){
Solution ob;
cout << (ob.canConstruct("true",4));
}输入值
"true"
输出结果
1
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便