Why my code exceed the time limit?


  • 0
    G

    I think the time complexity of my code and many of the versions in the discusses are similar. But how come the time exceeded limit error?

    public class Solution {
    	public String longestPalindrome(String s) {
            if(s==null||s.length()<=2) {
            	return s;
            }
            int len = s.length();
            int max = 0;
            int begin = 0; int finish = 0;
            int i = 0, j = 0;
        	int count = 0; 
            int st = i; int end = j;
            while(i < len-max){
            	j = i + max;
            	while(j < len){
                	count = 0; //do not forget this!
                    st = i; end = j;
            		while(st < end && s.charAt(st)==s.charAt(end)){
            		    count++;
                		st++;
                		end--;           	 
            		}
            		if(st > end && max<count*2){
            			max = count*2;
            			begin = i;
            		    finish = j;
            		}
            		else if(st == end && s.charAt(st)==s.charAt(end) && max<count*2+1){
            			max = count*2+1;
        				begin = i;
        		        finish = j;
            		}
            		j++;			
            	}
            	i++;
            }	
          return s.substring(begin, finish+1);
       }
    }
    

Log in to reply
 

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