Submission Result: Memory Limit Exceeded even though I have correct results?


  • 1
    A
    public class Solution {    public String reverseString(String s) {
            if (s.length() == 0)
            return " ";
            else if (s.length() == 1)
            return s;
            else {
            return reverseString(s.substring(1)) + s.substring(0,1);
            }
        } }
    

    For this solution, I get "Submission Result: Memory Limit Exceeded"

    Even though it gives the right results. What gives?


  • 0
    P

    Having Same problem with this

    public class ReverseString {
     static  void reverseString(String s) {
    
    String reversed="";
    int length=s.length();
    
    for(int i=length-1;i>=0;i--)
    {
        reversed+=s.charAt(i);
    }
    System.out.println(reversed);
    
    //return reversed;
    
        
    }
    
    public static void main(String []a)
    {
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        
        reverseString(s);
        
      //  System.out.println(s);
    }
    

    }


  • 0
    L

    Substring would copy the designated part of the string and create a new place in the memory. s.substring always needs new memory space and is not cleaned up before exiting the code.

    I think that is the reason why you are running out of memory here. Try using StringBuilder Class, that would be faster and memory efficient.


Log in to reply
 

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