This is for C++
A string is a palindrome if reverse of the string is same as the
original string. For example, “abba” is palindrome, but “abbc” is
not palindrome. Basically a string with a plane of symmetry in the
middle of it is considered a palindrome. For example, the following
strings are palindromic: "abbbbba", "abba", "abbcbba", "a", etc.
For this problem, you have an input string consisting of both
lowercase or uppercase characters. You are allowed to pick and
chose any of the characters from the input to construct a new
string palindrome. What is the length of the longest palindrome you
can construct?
Write a function that takes any arbitrary string, str, to obtain the length of the longest palindrome. You MUST make use of the following function signature:
input: "aBc"
output: 1
Explanation: you can take any single character as a palindrome. The longest one cannot go beyond 2 characters in this example because there are no duplicates.
input: "a"
output: 1
Explanation: the input is a palindrome
input: "BAA"
output: 3
Explanation: the longest one you can construct is "ABA" which has 3 characters.
CONSTRAINTS/ASSUMPTIONS
#include<bits/stdc++.h>
using namespace std;
int getlongestlength(string str)
{
int n = str.size();
int a[26][2]={0};
for(int i=0;i<n;i++)
{
if((str[i]<='z')&&(str[i]>='a'))
a[str[i]-'a'][0]++;
else
a[str[i]-'A'][1]++;
}
int length=0;
int odd=0;
for(int i=0;i<26;i++)
{
length +=a[i][0]/2+a[i]a[1]/2;
if((a[i][0]%2==1)||(a[i][1]%2==1))
odd=1;
}
length=2*length+odd;
return length;
}
int main()
{
cout<<getlongestlength("BBA");
return 0;
}
// i hope it is helpful for you
Get Answers For Free
Most questions answered within 1 hours.