OK in my Eclipse, but wrong in OJ


  • 1
    P

    My code runs fine in Eclipse (JDK1.6), but keeps getting wrong answers in OJ. The "wrong" case is
    [""], 2
    where [" "] is expected but my code in OJ returns [""]. I tested this case in my machine and it is OK, with the correct [" "] return. I wonder whether anythingis wrong in OJ or in my code.

    public class Solution {
    	String formLine(String[] words, int start, int end, int L) {/* start inclusive; end exclusive */
    		int numSpaces, lenWords=0;
    		for (int i=start;i<end;i++) {
    			lenWords += words[i].length();
    		}
    		StringBuffer sb = new StringBuffer(L);
    		numSpaces = L - lenWords;
    		sb.append(words[start]);
    		if (end-start!=1) {
    			int averageSpaces = numSpaces / (end-start-1);
    			int firstSpaces = numSpaces % (end-start-1);
    			char[] spaces = new char[Math.max(firstSpaces, averageSpaces)];
    			Arrays.fill(spaces, ' ');
    			sb.append(spaces, 0, firstSpaces);
    			for (int i=start+1;i<end;i++) {
    				sb.append(spaces, 0, averageSpaces);
    				sb.append(words[i]);
    			}
    		}
    		else {
    			char[] spaces = new char[numSpaces];
    			sb.append(spaces);
    		}
    		return sb.toString();
    	}
    	public ArrayList<String> fullJustify(String[] words, int L) {
    		ArrayList<String> al = new ArrayList<String>();
    		if (words.length==0) {
    			char[] ca = new char[L];
    			Arrays.fill(ca, ' ');
    			al.add(new String(ca));
    			return al;
    		}
    		int iw = 0; /* index in words */
    		int sum;
    		while (iw<words.length) {
    			sum = words[iw].length();
    			int iwi = iw + 1;
    			while (iwi<words.length && sum+words[iwi].length()+1<=L) {
    				sum += words[iwi++].length()+1;
    			}
    			if (iwi==words.length) {
    				al.add(formLine(words, iw, iwi,L));
    				return al;
    			}
    			al.add(formLine(words, iw, iwi, L));
    			iw = iwi;
    		}
    		return al;
    	}
    }

  • 0
    S

    I am not familiar with Java. I have no idea why this do not happen in your local.

    Apparently you missed one line to initialize space array.

    else {
        char[] spaces = new char[numSpaces];
        Arrays.fill(spaces, ' ');  // missing initialization.
        sb.append(spaces);
    }

  • 0
    P

    Thanks. I did forget the initialization. The interesting thing is that char is initialized as '\u0000', but it appears as a white space when I print it out in Eclipse. It is fixed now. BTW, there are so many other bugs in my original code...


Log in to reply
 

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