mardi 18 février 2020

Longest palindrome (dynamic programming) code fails with time-out for large inputs. How to improve it?

I am learning to solve dynamic programming problems on LeetCode recently. The problem in hand is to find the longest palindrome in any given string. My code works well for small sized input strings. But fails for very large size inputs. Looking forward for ideas to improve it.

Code :

#include <iostream>
#include <vector>

class Solution {
    public:
    std::string longestPalindrome(std::string s) {
        std::vector<std::string> sequence;
        std::string dummy, longest;

        for(auto it = s.begin(); it < s.end(); it++){
            dummy += *it;
            for(auto  it2 = it+1; it2 < s.end(); it2++) {
                dummy += *it2;
                sequence.push_back(dummy);
            }
            dummy = "";
        }
        for(auto &item : sequence) {
            for(auto it = item.rbegin(); it < item.rend(); it++) {
                dummy += *it;
            }
            if(item == dummy && item.size() > longest.size()) {
                longest = item;
            }
            dummy = "";
        }
        if (longest.empty())
            longest += *s.begin();
        return longest;
    }
};

int main() {
Solution solver;
std::cout << solver.longestPalindrome("babadhabab") << std::endl;
return 0;
}

Aucun commentaire:

Enregistrer un commentaire