longest palindromic substring recursive solution - c++

I am aware of solutions that uses the bottom up dynamic programing approach to solve this problem in O(n^2). I am specifically looking for a top down dp approach. Is it possible to achieve longest palindromic substring using a recursive solution?
Here is what I have tried but it fails for certain cases, but I feel I am almost on the right track.
#include <iostream>
#include <string>
using namespace std;
string S;
int dp[55][55];
int solve(int x,int y,int val)
{
if(x>y)return val;
int &ret = dp[x][y];
if(ret!=0){ret = val + ret;return ret;}
//cout<<"x: "<<x<<" y: "<<y<<" val: "<<val<<endl;
if(S[x] == S[y])
ret = solve(x+1,y-1,val+2 - (x==y));
else
ret = max(solve(x+1,y,0),solve(x,y-1,0));
return ret;
}
int main()
{
cin >> S;
memset(dp,0,sizeof(dp));
int num = solve(0,S.size()-1,0);
cout<<num<<endl;
}

For this case:
if(S[x] == S[y])
ret = solve(x+1,y-1,val+2 - (x==y));
it should be:
if(S[x] == S[y])
ret = max(solve(x + 1, y - 1, val + 2 - (x==y)), max(solve(x + 1, y, 0),solve(x, y - 1, 0)));
Because, in case you cannot create a substring from x to y, you need to cover the other two cases.
Another bug:
if(ret!=0){ret = val + ret;return ret;}
you should return ret + val and not modify ret in this case.
The main problem is you store the final val into dp[x][y], but this is not correct.
Example:
acabc , for x = 1 and y = 1, val = 3, so dp[1][1] = 3, but actually, it should be 1.
Fix:
int solve(int x,int y)
{
if(x>y)return 0;
int &ret = dp[x][y];
if(ret!=0){return ret;}
if(S[x] == S[y]){
ret = max(max(solve(x + 1, y),solve(x, y - 1)));
int val = solve(x + 1, y - 1);
if(val >= (y - 1) - (x + 1) + 1)
ret = 2 - (x == y) + val;
}else
ret = max(solve(x+1,y),solve(x,y-1));
return ret;
}

Longest Palindrome using Recursion in Javascript:
const longestPalindrome = str => {
if (str.length > 1){
let [palindrome1, palindrome2] = [str, str];
for (let i=0;i<Math.floor(str.length/2);i++) {
if(str[i]!==str[str.length-i-1]) {
palindrome1 = longestPalindrome(str.slice(0, str.length-1));
palindrome2 = longestPalindrome(str.slice(1, str.length));
break;
}
}
return palindrome2.length > palindrome1.length ? palindrome2 : palindrome1;
} else {
return str;
}
}
console.log(longestPalindrome("babababababababababababa"));

here is the python solution for this:
class Solution:
def longestPalindrome(self, s: str) -> str:
memo = {}
def isPalindrome(left,right):
state = (left, right)
if state in memo: return memo[state]
if left >= right:
memo[state] = True
return True
if s[left] != s[right]:
memo[state] = False
return False
memo[state] = isPalindrome(left+1, right-1)
return memo[state]
N = len(s)
result = ""
for i in range(N):
for j in range(i,N):
if (j-i+1) > len(result) and isPalindrome(i,j):
result = s[i:j+1]
return result

/*C++ program to print the largest palindromic string present int the given string
eg. "babad" contains "bab" and "aba" as two largest substring.
by occurance, "bab" comes first hence print "bab".
*/
#include<bits/stdc++.h>
using namespace std;
bool ispalindrome(string s)
{
int l = s.length()-1;
int r = 0;
while(l>r){
if(s[l]!=s[r])
return false;
l--;r++;
}
return true;
}
int main()
{
string str,str1,str3;
vector<string> str2;
cin>>str;
int len = str.length();
for(int i=0;i<len;i++)
{
for(int j=i;j<=len;j++)
{
str1 = "";
str1.append(str,i,j);
if(ispalindrome(str1)){
str2.push_back(str1);
}
}
}
int max = 0;
for(int i=0;i<str2.size();i++)
{
if(str2[i].length()>max){
max = str2[i].length();
str3 = str2[i];
}
}
cout<<"MAXIMUM LENGTH IS : "<<max<<"\nLARGEST PALINDROMIC STRING IS : "<<str3<<endl;
return 0;
}

#include <iostream>
using namespace std;
int ans=0;
bool fn(string &s,int i,int j){
if(i==j)
return 1;
if((j-i)==1&&s[i]==s[j])
return 1;
else if((j-i)==1&&s[i]!=s[j])
return 0;
if(s[i]==s[j]){
if(fn(s,i+1,j-1)){
ans=max(ans,j-i+1);
return 1;
}
else{
return 0;
}
}
else{
fn(s,i,j-1);
fn(s,i+1,j);
return 0;
}
}
int main() {
string s;
cin>>s;
int last=s.length()-1;
fn(s,0,last);
cout<<ans<<endl;
return 0;
}

Related

How to return negative value from function?

Below is the code snippet of reversing a positive of a negative number.But it always returning positive number of all negative numbers.If anyone know what's happening please do let me know.
code:
int reverse(int x){
int sub=0;
if(x<0){
while (x!=0){
sub = sub*10 + x%10;
x = x/10;
}
return (sub * -1);
}
else{
while (x!=0)
{
sub = sub*10 + x%10;
x = x/10;
}
return sub;
}
}
int main(){
int x = -123;
cout<<reverse(x);
cout<<c;
return 0;
}
Well:
return (sub * -1);
Sub will be -321 at this time. And -321 * -1 = 321.
The usual approach is to write code that handles non-negative numbers, and convert negative numbers to positive:
bool neg = false;
if (x < 0) {
neg = true;
x = -x;
}
// code to reverse the digits goes here
if (neg)
x = -x;
or, if you like recursive functions:
int reverse(int x) {
if (x < 0)
return -reverse(-x);
// code to reverse the digits goes here
return whatever;
}

What is wrong with my solution for code check problem CIELAB

I am doing a code chef practice prblem https://www.codechef.com/problems/CIELAB in easy category. But my solution is not working. The submit screen is showing : Status wrong Answer
#include <iostream>
using namespace std;
int input ();
int difference (int, int);
int calculateWrongAns (int);
int main()
{
int num1;
int num2;
num1 = input();
num2 = input();
int actualAns = difference(num1, num2);
int res = calculateWrongAns(actualAns);
cout << res;
return 0;
}
int input () {
int x;
cin >> x;
return x;
}
int difference (int x, int y) {
if (x > y) {
return x - y;
} else if (x < y) {
return y - x;
} else {
return 0;
}
}
int calculateWrongAns (int actualAns) {
int lastNumber = actualAns % 10;
int otherNumbers = actualAns / 10;
int res;
if (otherNumbers != 0) {
res = (otherNumbers * 10) + (lastNumber == 1 ? 2 : lastNumber - 1);
} else {
res = lastNumber == 1 ? 2 : lastNumber - 1;
}
return res;
}
Thanks in advance.
The line
res = lastNumber == 1 ? 2 : lastNumber - 1;
is wrong. You are splitting the result in last digit and other digits. If the last digit is 1, you are changing it to 2. If it not 1, you are subtracting 1. That means, if the result is 30, you are subtracting 1. The new result is 29. Two digits differ. That's not correct. You could use
int calculateWrongAns (int actualAns) {
return (actualAns % 10) == 0 ? actualAns + 1 : actualAns - 1;
}

Why I'm getting different results from GNU g++ and VC++

I'm trying to solve this problem in C++:
"Given a sequence S of integers, find a number of increasing sequences I such that every two consecutive elements in I appear in S, but on the opposite sides of the first element of I."
This is the code I've developed:
#include<iostream>
#include<set>
#include<vector>
using namespace std;
struct Element {
long long height;
long long acc;
long long con;
};
bool fncomp(Element* lhs, Element* rhs) {
return lhs->height < rhs->height;
}
int solution(vector<int> &H) {
// set up
int N = (int)H.size();
if (N == 0 || N == 1) return N;
long long sol = 0;
// build trees
bool(*fn_pt)(Element*, Element*) = fncomp;
set<Element*, bool(*)(Element*, Element*)> rightTree(fn_pt), leftTree(fn_pt);
set<Element*, bool(*)(Element*, Element*)>::iterator ri, li;
for (int i = 0; i < N; i++) {
Element* e = new Element;
e->acc = 0;
e->con = 0;
e->height = H[i];
rightTree.insert(e);
}
//tree elements set up
ri = --rightTree.end();
Element* elem = *ri;
elem->con = 1;
elem->acc = 1;
while (elem->height > H[0]) {
Element* succ = elem;
ri--;
elem = *ri;
elem->con = 1;
elem->acc = succ->acc + 1;
}
rightTree.erase(ri);
elem->con = elem->acc;
leftTree.insert(elem);
sol += elem->acc;
// main loop
Element* pE = new Element;
for (int j = 1; j < (N - 1); j++) {
// bad case
if (H[j] < H[j - 1]) {
///////
Element* nE = new Element;
nE->height = H[j];
pE->height = H[j - 1];
rightTree.erase(nE);
leftTree.insert(nE);
///////
li = leftTree.lower_bound(pE);
long ltAcc = (*li)->acc;
li--;
///////
ri = rightTree.lower_bound(pE);
long rtAcc = 0;
if (ri != rightTree.end()) rtAcc = (*ri)->acc;
ri--;
///////
while (ri != (--rightTree.begin()) && (*ri)->height > H[j]) {
if (fncomp(*ri, *li)) {
(*li)->con = rtAcc + 1;
(*li)->acc = rtAcc + 1 + ltAcc;
ltAcc = (*li)->acc;
--li;
}
else {
(*ri)->con = ltAcc + 1;
(*ri)->acc = ltAcc + 1 + rtAcc;
rtAcc = (*ri)->acc;
--ri;
}
}
while ((*li)->height > H[j]) {
(*li)->con = rtAcc + 1;
(*li)->acc = rtAcc + 1 + ltAcc;
ltAcc = (*li)->acc;
--li;
}
(*li)->con = rtAcc + 1;
(*li)->acc = rtAcc + 1 + ltAcc;
sol += (*li)->acc;
}
// good case
else {
Element* nE = new Element;
nE->height = H[j];
ri = rightTree.upper_bound(nE);
li = leftTree.upper_bound(nE);
rightTree.erase(nE);
if (li == leftTree.end() && ri == rightTree.end()) {
nE->con = 1;
nE->acc = 1;
}
else if (li != leftTree.end() && ri == rightTree.end()) {
nE->con = 1;
nE->acc = 1 + (*li)->acc;
}
else if (li == leftTree.end() && ri != rightTree.end()) {
nE->con = (*ri)->acc + 1;
nE->acc = nE->con;
}
else {
nE->con = (*ri)->acc + 1;
nE->acc = nE->con + (*li)->acc;
}
leftTree.insert(nE);
sol += nE->acc;
}
}
// final step
li = leftTree.upper_bound(*rightTree.begin());
while (li != leftTree.end()) {
sol++;
li++;
}
sol++;
return (int)(sol % 1000000007);
}
int main(int argc, char* argv[]) {
vector<int> H = { 13, 2, 5 };
cout << "sol: " << solution(H) << endl;
system("pause");
}
The main function calls solution(vector<int> H). The point is, when the argument has the particular value of H = {13, 2, 5} the VC++ compiled program give an output value of 7 (which is the correct one), but the GNU g++ compiled program give an output value of 5 (also clang compiled program behave like this).
I'm using this website, among others, for testing different compilers
http://rextester.com/l/cpp_online_compiler_gcc
I've tried to figure out the reason for this wierd behaviour but didn't found any relevant info. Only one post treat a similar problem:
Different results VS C++ and GNU g++
and that's why I'm using long long types in the code, but the problem persists.
The problem was decrementing the start-of-sequence --rightTree.begin()
As I found VC++ and GNU g++ does not behave the same way on above operation. Here is the code that shows the difference, adapted from http://www.cplusplus.com/forum/general/84609/:
#include<iostream>
#include<set>
using namespace std;
struct Element {
long long height;
long long acc;
long long con;
};
bool fncomp(Element* lhs, Element* rhs) {
return lhs->height < rhs->height;
}
int main(){
bool(*fn_pt)(Element*, Element*) = fncomp;
set<Element*, bool(*)(Element*, Element*)> rightTree(fn_pt);
set<Element*, bool(*)(Element*, Element*)>::iterator ri;
ri = rightTree.begin();
--ri;
++ri;
if(ri == rightTree.begin()) cout << "it works!" << endl;
}

How to I reduce a chain of if statements?

How to I reduce a chain of if statements in C++?
if(x == 3) {
a = 9876543;
}
if(x == 4) {
a = 987654;
}
if(x == 5) {
a = 98765;
}
if(x == 6) {
a = 9876;
}
if(x == 7) {
a = 987;
}
if(x == 8) {
a = 98;
}
if(x == 9) {
a = 9;
}
This is the example code.
You can generate this value mathematically, by using integer division:
long long orig = 9876543000;
long long a = orig / ((long) pow (10, x));
EDIT:
As #LogicStuff noted in the comments, it would be much more elegant to subtract 3 from x, instead of just multiplying orig by another 1000:
long orig = 9876543;
long a = orig / ((long) pow (10, x - 3));
With an array, you may do:
if (3 <= x && x <= 9) {
const int v[] = {9876543, 987654, 98765, 9876, 987, 98, 9};
a = v[x - 3];
}
Something like:
#include <iostream>
#include <string>
int main() {
int x = 4;
int a = 0;
std::string total;
for(int i = 9; i > 0 ; --i)
{
if(x <= i)
total += std::to_string(i);
}
a = std::stoi(total, nullptr);
std::cout << a << std::endl;
return 0;
}
http://ideone.com/2Cdve1
If the data can be derived, I'd recommend using one of the other answers.
If you realize their are some edge cases that end up making the derivation more complicated, consider a simple look-up table.
#include <iostream>
#include <unordered_map>
static const std::unordered_multimap<int,int> TABLE
{{3,9876543}
,{4,987654}
,{5,98765}
,{6,9876}
,{7,987}
,{8,98}
,{9,9}};
int XtoA(int x){
int a{0};
auto found = TABLE.find(x);
if (found != TABLE.end()){
a = found->second;
}
return a;
}
int main(){
std::cout << XtoA(6) << '\n'; //prints: 9876
}

C++ Not Counting white beands

I need some help. I'm writing a code in C++ that will ultimately take a random string passed in, and it will do a break at every point in the string, and it will count the number of colors to the right and left of the break (r, b, and w). Here's the catch, the w can be either r or b when it breaks or when the strong passes it ultimately making it a hybrid. My problem is when the break is implemented and there is a w immediately to the left or right I can't get the program to go find the fist b or r. Can anyone help me?
#include <stdio.h>
#include "P2Library.h"
void doubleNecklace(char neck[], char doubleNeck[], int size);
int findMaxBeads(char neck2[], int size);
#define SIZE 7
void main(void)
{
char necklace[SIZE];
char necklace2[2 * SIZE];
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
initNecklace(necklace, SIZE);
doubleNecklace(necklace, necklace2, SIZE);
maxBeads = findMaxBeads(necklace2, SIZE * 2);
checkAnswer(necklace, SIZE, maxBeads);
printf("The max number of beads is %d\n", maxBeads);
}
int findMaxBeads(char neck2[], int size)
{
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
for(brk = 0; brk < 2 * SIZE - 1; brk++)
{
leftCount = rightCount = 0;
rightI = brk;
rightColor = neck2[rightI];
if(rightI == 'w')
{
while(rightI == 'w')
{
rightI++;
}
rightColor = neck2[rightI];
}
rightI = brk;
while(neck2[rightI] == rightColor || neck2[rightI] == 'w')
{
rightCount++;
rightI++;
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
if(leftI == 'w')
{
while(leftI == 'w')
{
leftI--;
}
leftColor = neck2[leftI];
}
leftI = brk - 1;
while(leftI >= 0 && neck2[leftI] == leftColor || neck2[leftI] == 'w')
{
leftCount++;
leftI--;
}
}
totalCount = leftCount + rightCount;
if(totalCount > maxCount)
{
maxCount = totalCount;
}
}
return maxCount;
}
void doubleNecklace(char neck[], char doubleNeck[], int size)
{
int i;
for(i = 0; i < size; i++)
{
doubleNeck[i] = neck[i];
doubleNeck[i+size] = neck[i];
}
}
I didn't study the code in detail, but something is not symmetric: in the for loop, the "left" code has an if but the "right" code doesn't. Maybe you should remove that -1 in the for condition and add it as an if for the "right" code:
for(brk = 0; brk < 2 * SIZE; brk++)
{
leftCount = rightCount = 0;
if (brk < 2 * SIZE - 1)
{
rightI = brk;
rightColor = neck2[rightI];
//...
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
//...
}
//...
Just guessing, though... :-/
Maybe you should even change those < for <=.