2

I was solving this longest palindromic substring problem on leetcode and I followed the dynamic programming approach by creating one n*n boolean table(which I guess is also the standard solution to this) and successfully solved it but I was just wondering if this problem can be done using the technique that we use in finding out longest common subsequence or to be more precise, just wish to know whether the LCS problem is parent question of this problem as well like in the case of longest palindromic subsequence which can be solved easily through LCS by taking one another string as reverse of original string.

I searched web but didn't find any solution using LCS technique that's why thought of asking it here. If it is possible to solve using lcs technique then please provide the approach or else some good reason for why it can't be solved using LCS.

1 Answers1

1

I actually solved this exact problem in the exact way you wanted! We can do it in the LCS method using a single array, but the overhead in this is that you will have to check every combination if it is a palindrome manually. See below for the solution by this way. This was accepted on LC as well.

    public String longestPalindrome(String s) {
        int maxlen = 1;
        int len = s.length();
        String[] dp = new String[len];
        dp[0] = s.substring(0,1);
        for (int i = 1; i < len; i++) {
            dp[i] = dp[i-1];
            for (int j = 0; i - j >= maxlen; j++) {
                if (s.charAt(j) != s.charAt(i)) continue;
                if (isPal(s.substring(j, i + 1))) {
                    dp[i] = s.substring(j, i + 1);
                    maxlen = i - j;
                    break;
                }
            }
        }
        return dp[len-1];
    }
    
    public boolean isPal(String s) {
        for (int i = 0; i < s.length()/2; i++) {
            if (s.charAt(i) != s.charAt(s.length()-1-i)) return false;
        }
        return true;
    }

Emma
  • 27,428
  • 11
  • 44
  • 69
berlin
  • 506
  • 4
  • 14
  • @emma I didn't actually understood your solution really well so I'm sharing the one coded by me which failed on the given testcase at leetcode **aacabdkacaa** . [here](https://leetcode.com/submissions/detail/415176590/) is the link to my code which failed on the above testcase. The correct output should be "aca" but my code gives "aaca" reading the first four characters from the front and last 4 from the end of the string. Please help me correct my code. – NITESH SHARMA Oct 31 '20 at 10:17
  • 1
    @NITESHSHARMA i wrote this solution not emma. the link does not work i get 404 not found, maybe you could try again? – berlin Oct 31 '20 at 15:27