Longest Palindrome in a String | Practice | GeeksforGeeks

Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index).

Example 1:
Input:
S = "aaaabbaa"
Output: aabbaa
Explanation: The longest Palindromic
substring is "aabbaa".

Example 2:
Input: 
S = "abc"
Output: a
Explanation: "a", "b" and "c" are the 
longest palindromes with same length.
The result is the one with the least
starting index.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S.

Expected Time Complexity: O(|S|2).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ |S| ≤ 103
0
spiderman694 hours ago
Easy solution without DP
 string longestPalin (string S) {
        // code here
        int length1= INT_MIN; 
           string ans="";
       for(int i=0;i<S.length();i++)
       {
           int start = i-1;
           int end = i+1;
          
           
           while(start>=0 && end<=S.length()-1)
           {
               if(S[start] == S[end])
                {
                    start--;
                    end++;
                }else break;
           }
           
           int l1 = (end-start)-1;
           if(l1>ans.length())
           {
               ans = S.substr(start+1,l1);
           }
           
           start = i-1;
           end = i;
            
           while(start>=0 && end<=S.length()-1)
           {
               if(S[start] == S[end])
                {
                    start--;
                    end++;
                } else break;
           }
           
           int l2 = (end-start)-1;
           if(l2>ans.length())
           {
               ans = S.substr(start+1,l2);
           }
       }
       
       return ans;
    }
0
botty11 day ago
class Solution {
  public:
    // Data Members
  	int right;
	int left;
	string maxPalin = "";
	int maxLen = 1;
	// Data Members

	void extractPalin(string& S, int low, int high) {
		right = high;
		left = low;
        int strlen = S.length();
        while(left >= -1 or right <= strlen) {
        	if(left == -1 or right == strlen or S[right] != S[left]) {
        		int temp = right - left - 1;
        		if(temp > maxLen) {
        			maxLen = temp;
        			maxPalin = S.substr(left + 1, maxLen);
        		}
        		break;
        	}
        	left--;
        	right++;
        }
	}

    string longestPalin (string S) {
    	int strlen = S.length();
    	string tempStr = S + " ";
    	maxPalin = S[0];
        for (int i = 0; i < strlen; ++i)
        {
            extractPalin(S, i, i);
        	if(tempStr[i] == tempStr[i + 1]) extractPalin(S, i, i + 1);
        }
        return maxPalin;
    }
};
0
aryabamboli20022 days ago
Easy solution with Dp C++
 
string longestPalin (string S) {       int n = S.length();       int dp[n][n];       for(int i=0;i<n;i++){           for(int j=0;j<n;j++){               if(i==j){                   dp[i][j]=1;               }               else if(j==i+1){                   if(S[i]==S[j]){                       dp[i][j]=1;                   }else{                       dp[i][j]=0;                   }               }else{                   dp[i][j]=0;               }           }       }       string str="";       int ans=INT_MIN, k, previ=INT_MAX;       for(int i=n-1;i>=0;i--){           for(int j=n-1;j>=0;j--){               if(j-i>1){                   if(S[i]==S[j] && dp[i+1][j-1]==1){                       dp[i][j]=1;                   }               }               if(dp[i][j]==1 && (j-i+1>ans or (j-i+1==ans && i<previ))){                   ans=j-i+1;                   k=i;                   previ=i;                   str="";                   while(k<=j){                       str+=S[k];                       k++;                   }               }           }       }       return str;
0
om shankar ohdar3 days ago
Python without Dp in N^2:    def longestPalin(self, S):       # code here       start = 0       maxL = 1       low = 0       high = 0              for i in range(1, len(S)):           # for substring with odd length           low = i-1           high = i           while low >=0 and high < len(S) and S[low] == S[high]:               if (high -low + 1) > maxL:                   start = low                   maxL = high - low + 1                                  low -= 1               high += 1                          # for substring with even length           low = i-1           high = i+1           while low >= 0 and high < len(S) and S[low] == S[high]:               if (high - low + 1) > maxL:                   start = low                   maxL = high - low + 1                                  low -= 1               high += 1                      return S[start: start+maxL]
0
rishitharapolu21
This comment was deleted.
0
kamresh4853 days ago
    bool isPalindrome(string&S,int l,int r){
       while(l<r)
           if(S[l++]!=S[r--])
               return false;
       return true;
   }
   
   string longestPalin (string S) {
       string max=S.substr(0,1);
       for(int i=0;i<S.length()-1;i++)
           for(int j=i+1;j<S.length();j++)
               if(isPalindrome(S,i,j) && max.length()<j-i+1)
                   max=S.substr(i,j-i+1);
       return max;            
   }
0
luvgupta76695 days ago
Simple Working Java Solution-

    static String longestPalin(String S) {
        if(S.length() < 2){
            return S;
        }
        String max="";
        for(int i=0; i<S.length()-1; i++){
            String odd = findPalindrome(S, i, i);
            String even = findPalindrome(S, i, i+1);
            if (odd.length() > max.length()) {
                max = odd;
            }
            if (even.length() > max.length()) {
                max = even;
            }
        }
        return max;    
    }
    static String findPalindrome(String s, int left, int right) {
        while(left>=0 && right<s.length() && s.charAt(left) == s.charAt(right)){
            left--; right++;
        }
        return s.substring(left+1, right);
    }
-1
rupendrasaraswat5 days ago
 static String longestPalin(String S){       // code here       String str="";       for(int i=0;i<S.length();i++){           for(int j=i+1;j<=S.length();j++){               String a=S.substring(i,j);               if(palin(a))                   if(a.length()>str.length())                       str=a;           }       }       return str;   }   public static boolean palin(String s){       int len=s.length();       for(int i=0;i<len/2;i++){           if(s.charAt(i)!=s.charAt(len-1-i))               return false;       }       return true;   }
0
nitind3566 days ago
Simple C++ Solution using Dynamic programming
string longestPalin (string s) {
        bool dp[s.length()][s.length()];
        int st=0,ed=0,l=0;
        for(int g=0;g<s.length();g++)
        {
            for(int i=0,j=g;j<s.length();i++,j++)
            {
                if(g==0)
                    dp[i][j]=true;
                else if(g==1)
                {
                    if(s[i]==s[j])
                    {
                        dp[i][j]=true;
                    }
                    else
                    {
                        dp[i][j]=false;
                    }
                }
                else
                {
                    if(s[i]==s[j] && dp[i+1][j-1]==true)
                    {
                        dp[i][j]=true;
                    }
                    else
                    {
                        dp[i][j]=false;
                    }
                }
                if(dp[i][j] && (g+1)>l)
                {
                    st=i;
                    ed=j;
                    l=g+1;
                }
            }
        }
        return s.substr(st,ed-st+1);
    }
-4
rrodwal221 week ago
bool isPalindrome(string str, int s, int e){     while(s < e){         if(str[s] != str[e]){             return false;         }         s++;         e--;     }     return true; }  public:   string longestPalin (string S) {       int n = S.length();       int maxLen = 0;       string ans = "";              if(n == 1){           return S;       }       for(int i = 0; i<n-1; i++){           for(int j = i; j<n; j++){                              if(isPalindrome(S, i, j) && maxLen < (j-i+1)){                                      maxLen = j-i+1;                   ans = S.substr(i, j-i+1);               }           }       }       return ans;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.