Time Exceed Error with StringBuffer


  • 0
    A

    Hi everyone,

    My code causes a Time Exceeded Error because of StringBuffer.

    public String convert(String s, int nRows) {
        if (s == null || s.length() <= 0 || nRows <= 1 || nRows >= s.length()) return s;
        StringBuffer[] rows = new StringBuffer[nRows];
        Arrays.fill(rows, new StringBuffer(s.length()));
        int m = nRows * 2 - 2;
        for (int i = 0; i < s.length(); i++) {
            int x = i % m;
            if (x < nRows) rows[x].append(s.charAt(i));
            else rows[m - x].append(s.charAt(i));
        }
        for (int i = 1; i < nRows; i++)
            rows[0].append(rows[i]);
        return rows[0].toString();
    }
    

    This code can be accepted if replace StringBuffer with String.

    However, I am considering that StringBuffer should be more efficient than String on concatenating. Or should I use StringBuilder?
    Does anyone have any idea about it?


  • 0
    Y

    I think the problem is at

    Arrays.fill(rows, new StringBuffer(s.length()));
    

    By doing this you will not assign each StringBuilder a new StringBuilder(s.length()). Instead all StringBuffers point to the same StringBuilder object.

    Try this may solve your Time Exceeded Error.

    StringBuilder[] sbBuilders = new StringBuilder[nRows];
    for(int i = 0; i < nRows; i++){
    	sbBuilders[i] = new StringBuilder();
    }
    

Log in to reply
 

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