I am unable to find an issue with this code for reverseString I worte in JAVA. OJ says its wrong.


  • 0
    D
    private String reverseWords(String s){
    
    	if(s.trim().length()==0){
    		 return s.trim();
    	 }
    	String[] strings = s.trim().split(" ");
    	LinkedList<String> stringList = new LinkedList<String>();
    	for (String str : strings) {
    		if (!str.equals("")) {
    			stringList.add(str);
    			stringList.add(" ");
    		}
    	}
    	StringBuilder builder = new StringBuilder();
    	while(stringList.size()>0)
    	builder.append(stringList.removeLast());
    	System.out.println(builder);
    	String output=builder.toString().trim();
    	return output;
    }

  • 0
    M

    how does it say it's wrong? Wrong answer?


  • 1
    N

    Add trim() when u r trying to return the output or do some process for the leading space of ur output.

    If u have input: "a bc def" the output based on ur code would be " def bc a"


  • 0
    D

    Thanks for your reply @nino. I put trim already. The output u show is the expected output.


  • 0
    D

    Hey @mike3.. Thanks for replying..

    The error looks like this:
    Input:"a"
    Output:a
    Expected : "a"
    It says wrong answer. What isthe issue here.It seems my eyes fail to grasp something here...


  • 1
    M

    4th to last line of code:

    System.out.println(builder);
    

    This prints out the result, but is not the same as the String being returned. That's why your output is a string without the quotes. Leetcode's judge works by taking the first output from your program and treating that as your result. Take out the print statements and you shouldn't have this problem.


  • 0
    D

    Thanks so much@mike3.. this solved it.Its pretty bizarre, that this happens that way. In other words, We shouldn't be having any sysouts or prints statements. Right?


  • 0
    D

    I got the solution thanks to mike3, upvoting your answer too as trim was required as well :)


  • 0
    M

    Right. I'm not on the team behind the site, so I'm going off what they've said on other problems about how it works. The first output is always treated as the answer, and also always treated as wrong, as it is a printed output and not an object or data type.


  • 0
    D

    Right. Well I would never have guessed this. So really... thanks a ton!!!


Log in to reply
 

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