TLE Problem. Java. Why is this way not efficient?


  • 0
    S
    public class Solution {
    public String longestPalindrome(String s) {
        if (s == null) return null;
        if (s.length() ==0) return "";
        if (s.length() ==1) return s;
        int begin= 0;
        int end;
        for(int length = s.length();length>1;length--){
            end = begin+length;
            for(begin = 0; end<s.length();begin++){
                end = begin+length;
                if(isPalindrome(s.substring(begin,end)))
                    return s.substring(begin,end);
            }
        }
        return s.charAt(0)+"";
    }
    public static boolean isPalindrome(String s){
        
        int start = 0;
        int end = s.length()-1;
        while (start<=end){
            if (s.charAt(start)==s.charAt(end)){
                start++; end--;
            }else{
                return false;
            }
        }
        return true;
    }
    

    }


  • 1
    G

    This is O(n^3) solution. There is O(n) solution


Log in to reply
 

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