0

Leetcode q: https://leetcode.com/contest/biweekly-contest-69/problems/longest-palindrome-by-concatenating-two-letter-words/

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!

jeremy
  • 59
  • 7
  • Please add a programming-language tag. – c0der Jan 09 '22 at 05:07
  • Won't the map length stay the same once you've gone to the bottom the first time? It's causing the search to bail early. – shawnt00 Jan 09 '22 at 05:52
  • hmm i thought it wouldnt cuz i set visited[i] to false after making that recursive call but ill output map length out and check for each iteration. Thanks @shawnt00 – jeremy Jan 10 '22 at 09:35

0 Answers0