how can i NOT get a Time Limit Exceeded problem?


  • 0
    S

    I need a help on my style of coding.
    I think I got the proper logic but when I submit the solution,
    it gets Time Limit Exceeded issue.
    My coding is as below and it would be great if I could a feedback.

    '''
    public class Solution {
    public String longestPalindrome(String s) {
    String maxResult ="";
    String result = "";
    boolean dupFlg =false;
    char[] chars = s.toCharArray();

        for (int i=0;i<chars.length;i++) {
            for (int j=i+1;j<chars.length;j++) {
                if (s.substring(i,j+1).equals((new StringBuffer(s.substring(i,j+1))).reverse().toString())) { 
                    dupFlg= true;
                    result= s.substring(i,j+1);
                    if(result.length() > maxResult.length()) {
                        maxResult = result;
                    }
                }
            }
        }
        
    if (!dupFlg) { //if there is no duplication, the string is the 1st char
        maxResult = s.substring(0,1);
    }
    return maxResult;  
    }
    

    }
    '''


Log in to reply
 

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