What is wrong with my solution? How can I optimize it?


  • 0
    S

    I seem to not pass the extremely long inputs with the following code:

    public String convertToPalindrome(String str)
    {
    	if(isPalindrome(str))
    	{
    		return str;
    	}
    	String front = “”;
    	for(int i = str.length - 1; i >= 0; i--)	
    	{
    		front = front + str.charAt(i);
    		if(isPalindrome(front + str))
    		{
    			return (front + str);
    		}
    	}
    	return (front + str);
    }
    
    public boolean isPalindrome(String str)
    {
    	String reverse = str.toCharArray().reverse().toString();
    	if(str.equals(reverse))
    	{
    		return true;
    	}
    	return false;
    }

  • 0
    E

    it is O(n^2), i guess the judge looking for O(n)


Log in to reply
 

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