Longest Palindromic Substring


Today we will discuss a common problem. The problem is, you are given a string S, you have to find the longest palindromic substring in S.
For example, S = abcbsd, here our desired answer is bcb with length 3.

Solution: This problem can be solved in many ways. One of them is DP solution and another is Expand Around Center.

DP: DP
solution is a very straight cut solution. We go through all the substrings of the main string S and check each substring is palindrome or not and find the longest substring if it is palindrome. Here we do DP in the palindrome checking part. Here is the Code. Complexity O(n^2).


  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string s;
  5. int dp[1005][1005]; ///dp[l][r] means is substring s[l...r] is a palindrome or not
  6.  
  7. int isPalindrome(int left,int right)
  8. {
  9. if( left >= right )
  10. return 1;
  11. if( dp[left][right] != -1 )
  12. return dp[left][right];
  13. int result = 0;
  14. if( s[left] == s[right] )
  15. result = isPalindrome(left+1 , right-1);
  16. return dp[left][right] = result;
  17. }
  18.  
  19. int main()
  20. {
  21. memset(dp , -1 , sizeof(dp));
  22. int n, mx = 0, start = 0;
  23. string ans;
  24. cin >> s;
  25. n = (int)s.size();
  26.  
  27. for(int i=0 ; i<n ; i++){
  28. for(int j=i ; j<n ; j++){
  29. if(mx < j-i+1 && isPalindrome(i,j))
  30. {
  31. mx = j-i+1;
  32. start = i;
  33. }
  34. }
  35. }
  36. ans = s.substr(start, mx);
  37. cout << ans << endl;
  38. return 0;
  39. }
  40.  
Expand Around Center: This solution is based on the center of the palindrome string. We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n − 1 such centers. Complexity O(n^2). The code is right below.

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int extendPalindrome(string &s, int l, int r)
  5. {
  6. while(l >= 0 && r <s.size() && s[l] == s[r] )
  7. {
  8. l--; r++;
  9. }
  10. return r-l-1;
  11. }
  12. int main()
  13. {
  14. string s;
  15. cin >> s;
  16. bool even = 0;
  17. int Max = 0, num, n = (int) s.size()-1;
  18. for(int i = 0; i < n; i++)
  19. {
  20. int len1 = extendPalindrome(s,i,i);
  21. int len2 = extendPalindrome(s,i,i+1);
  22. int tmp = max(len1 , len2);
  23. if(Max < tmp)
  24. {
  25. Max = tmp;
  26. if( len1 >= len2 ) // odd palindrome
  27. {
  28. num = i;
  29. even = 0;
  30. }
  31. else // even palindrome
  32. {
  33. num = i;
  34. even = 1;
  35. }
  36. }
  37. }
  38. string ans = "";
  39. if(even)
  40. {
  41. int len = Max;
  42. Max /=2;
  43. ans = s.substr(num- Max+1, len);
  44. }
  45. else
  46. {
  47. int len = Max;
  48. Max /=2;
  49. ans = s.substr(num - Max, len);
  50. }
  51. cout << ans << endl;
  52. return 0;
  53. }
  54.  

Comments

Popular posts from this blog

URI 2994 Solution

URI 2996 Solution