Why using stringbuilder cause runtime error?


  • 0
    J

    I use StringBuilder to append the character,but when i test the program on the local machine,it cause "java.lang.OutOfMemoryError: Java heap space",I know it it because allocate too large size array,but why?

    public class Solution {
    	public String convert(String s, int nRows) {
    		if(s==null)
    			return "";
    		int length=s.length();
    		if(nRows==1||length<=nRows) 
    			return s;
    		StringBuilder sb=new StringBuilder();
             int step=2*nRows-2;   
             for(int i=0;i<nRows;++i){
             	int interval=step-2*i;   
             	for(int j=i;j<length;j+=step){    
             		sb.append(s.charAt(j));
             		while(interval<step&&interval>0&&j+interval<length){
             			sb.append(s.charAt(j+interval));
             		}   
             	}
    
             }       
             return sb.toString();
         }
    }

  • 0
    M

    Are you sure you don't get into an infinite while loop?


  • 0
    J

    uh... I should replace the while to if,thx!


Log in to reply
 

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