

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct K Palindrome Strings in C++
Suppose we have a string s and a number k. We have to construct k non-empty palindrome strings using all the characters in s. So here we have to check whether we can use all the characters in s to construct k palindrome strings or not.
So, if the input is like "true", k = 4, then the output will be True, as the only possible solution is to put each character in a separate string.
To solve this, we will follow these steps −
n := size of s
if n < k, then −
return false
if n is same as k, then −
return true
Define one map
for each character c in s
(increase m[c] by 1)
odd := 0
for each key-value pair it in m −
odd := odd + (value of it AND 1)
return true when odd <= k, otherwise false
Example
Let us see the following implementation to get a better understanding −
#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)); }
Input
"true"
Output
1
- Related Questions & Answers
- K-Similar Strings in C++
- Construct objects from joining two strings JavaScript
- Function to find out palindrome strings JavaScript
- Joining strings to form palindrome pairs in JavaScript
- N’th palindrome of K digits in C++
- Count all Palindrome Sub-Strings in a String in C++
- Program to find value of K for K-Similar Strings in C++
- Python program to concatenate Strings around K
- Construct DFA with Σ= {0,1} accepts all strings with 0.
- Construct DFA for strings not ending with "THE"
- Program to split two strings to make palindrome using Python
- Construct a Turing machine for L = {aibjck | i*j = k; i, j, k ≥ 1}
- Construct a Turing machine for L = {aibjck | i>j>k; k ≥ 1}
- Program to find smallest value of K for K-Similar Strings in Python
- Construct the full k-ary tree from its preorder traversal in C++
Advertisements