Longest Palindrome in String Time Limit exceeded


  • 0
    public String longestPalindrome(String s) {
        
        if(s.length()==1)
        return s;
     
        StringBuilder ans2;
        int c=0;
        int m=0;
        String ans="";
        String ans1="";
        int e=0,e1=0;
        int rtk=0;
        for(int k=0;k<s.length();k++){
        
        for(int i=k,j=s.length()-1;i<j;)
        {
            
            if(s.charAt(i)==s.charAt(j))
              { 
               ans=ans+s.charAt(i);
               i++;
               j--;
               c++;
                  e=i;
                  e1=j;
              continue;
              }
              else{
                 
                  if(c==0)
                   {  
                       j--;
                          e=i;
                          e1=j;
                       continue;
                   }
                  ans="";
              i=i-c;
             j=j+c-1;
              c=0;
                 e=i;
                 e1=j;
              continue;
              }
           
        }
       if(e==e1)
       ans=ans+s.charAt(e);
         ans2=new StringBuilder (ans);
          ans2=ans2.reverse();
             if(e==e1)
         ans=ans+ans2.substring(1,ans2.length());
         else
        ans=ans+ans2.substring(0,ans2.length());
        
        
        if(ans.length()>ans1.length())
        ans1=ans;
       c=0;
       ans="";
            
        }
    
      return ans1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.