Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
C++ program to find string with palindrome substring whose length is at most k
Suppose we have two numbers n and k. Let we are trying to generate a string S with only three types of characters 'a', 'b' and 'c'. The maximum length of a substring of the string S that is a palindrome which does not exceeds k.
So, if the input is like n = 3; k = 2, then the output will be "aab", because its length is 3 and the palindrome substring is "aa" with length at least 2. (other answers are also possible).
Steps
To solve this, we will follow these steps −
S := a blank string j := 0 for initialize i := 0, when i < n, update (increase i by 1), do: S := S concatenate (j + ASCII of 'a') as character j := (j + 1) mod 3 return S
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
string solve(int n, int k) {
string S = "";
int j = 0;
for (int i = 0; i < n; i++) {
S += j + 'a';
j = (j + 1) % 3;
}
return S;
}
int main() {
int n = 3;
int k = 2;
cout << solve(n, k) << endl;
}
Input
3, 2
Output
abc
Advertisements
