My Solution:
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPalindrome(string str){
int n=str.size();
for(int i=0;i<=n/2;i++){
if(str[i]!=str[n-1-i]){
return false;
}
}
return true;
}
int ans=0;
void dfs(string curStr, unordered_map<int,bool> visited, vector<string> &words){
//Snippets for debugging:-
// cout<<curStr<<endl;
// cout<<"Visited map:- \n";
// for (auto i : visited)
// cout << i.first << " is " << i.second
// << endl;
//
// cout<<endl;
//Excluding this gives the correct answer, idk why it dosent work otherwise
//P1:-
// if(visited.size() == words.size()){
// return;
// }
for(int i=0;i<words.size();i++){
if(!visited[i]){
string newStr = curStr + words[i]; //chk?
if(isPalindrome(newStr)){
if(ans<newStr.size()){
ans=newStr.size();
}
}
visited[i]=true;
dfs(newStr, visited, words);
visited[i]=false;
}
}
}
int longestPalindrome(vector<string>& words) {
unordered_map<int,bool> visited;
dfs("", visited, words);
return ans;
}
};
Main Function with invocation:-
int main(){
Solution s1;
vector<string> tc{"lc","cl","gg"};
cout<<"ANS:"<<s1.longestPalindrome(tc);
return 0;
}
I ran my code for this test case shown in main but whenever I exclude the Part Called P1 (or the return statement in the void fn called dfs), it gives the right answer of "6." However, when that snippet P1 is included, it gives an answer "4"
I have no why this is happening. I'm guessing it's something silly but it'd mean a lot if someone could help. Thanks!