JAVA Runtime exceeded, can someone help me to understand why my code exceeded the runtime?


  • 0
    S
    class Solution {
        public String longestPalindrome(String s) {
            String result = "";
            if (s == null || s.length() == 0){
                return result;
            }
            result = "" + s.charAt(0);
            int length = s.length();
            for (int i = 0; i < length; i ++){
                for (int j = i + result.length(); j < length; j ++){
                    if (s.charAt(i) == s.charAt(j)){
                        if (j-i+1 > result.length() && isPalindrome(s.substring(i+1,j))){
                            // int x = j-i+1;
                            // System.out.println("j-i+1 = " + x);
                            result = s.substring(i,j+1);
                        }
                    }
                }
            }
            return result;
        }
        public boolean isPalindrome(String s){
            int length = s.length();
            for (int i = 0; i < length/2; i ++){
                if (s.charAt(i) != s.charAt(length - 1 - i)){
                    return false;
                }
            }
            return true;
        }
    }
    

    Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"


  • 0
    M

    @Stevan0102 Your solution contains 3 nested loops giving O(n^3) runtime, even though your palindrome loop is cut in half. Try to use a solution that requires a maximum of 2 nested loops to prevent the runtime exceeding.


Log in to reply
 

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