Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- string longestPalin (string s) {
- int n = s.size();
- vector <vector <bool>> dp(n,vector<bool>(n,false));
- int max_len = 1,start = 0;;
- for (int i = 0; i < n; ++i) //one length substring will always be palindrome
- dp[i][i] = true;
- for (int i = 0; i < n - 1; ++i) {
- if (s[i] == s[i + 1]) { //two length substring will be only palindrome if repeating eg aa,bb,cc
- dp[i][i + 1] = true;
- if(max_len<2){ start = i; max_len = 2; }
- }
- }
- /*so for abc:- a,b,c,ab,bc result are already in dp table,so for satisfying the palindromic
- condition inside elemetnts must be palindrome so if assume a==c then b must be palindrome for being abc
- palindrome that is already in dp table if that is palindrome or dp[i+1][j] where i and j is
- corner index of current substring is true then we will compare a and c,if same then abc is
- palindrome.
- eg2 sbcbs,find bcb is palindrome or not using dp table i.e dp[i+1][j-1] if yes,then compare
- ith and jt element,is same then it is palindrome else make dp[i][j]=false ie. not a palindrome
- */
- for (int k = 3; k <= n; ++k) { //cheking palindromne length from 3 to n
- for (int i = 0; i < n - k + 1; ++i) { //checking for every starting point
- int j = i + k - 1; //ending point for current considered substring
- if (dp[i + 1][j - 1] && s[i] == s[j]) {
- dp[i][j] = true;
- if (k > max_len) {
- start = i;
- max_len = k;
- }
- }
- }
- }
- return s.substr(start,max_len);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement