JAVA Time Limit Exceeded - What's my time and space complexity ?


  • 0
    Y
    //It is strange that my code cannot pass the submission, while it can run that test case in 37 ms. 
    //Could anyone explain it? Thanks a lot! 
    public class Solution {
    public String longestPalindrome(String s) {
        if(s == null || s.isEmpty())
            return s;
        int pos = s.length() - 1;
        int max = 1;
        String result = s.substring(0, 1);
        while(pos >= 0){
            int first = pos-1;
            int second = pos+1;
            while(first > -1 && s.substring(pos, pos+1).equals(s.substring(first, first + 1))){
                first --;
                if(second < s.length() && s.substring(pos, pos+1).equals(s.substring(second, second + 1))){
                    second++;
                } else{
                    break;
                    
                }
            }
            while (first > -1 && second < s.length() && s.substring(first, first+1).equals(s.substring(second, second + 1))){
                first --;
                second ++;
            }
            if(second - first - 1 > max){
                max = second - first - 1;
                result = s.substring(first+1, second);
                if(max == s.length())
                    break;
            }
            pos--;
        }
        return result;
    }
    

    }


Log in to reply
 

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