On my pc the solution works perfectly, the online judge complains. What I'm missing?


  • 0
    L

    Hi everyone, I just wrote this code as a solution for the reverse words question.
    Actually, it is working fine on my pc, while it is not accepted by the online judge, claiming that on input " 1" my code produces "1 " as an output.
    What I'm doing wrong?

    `public class Solution {
        public String reverseWords(String s) {
            String result = "";
            if (s.equals(""))
                return s;
            else {
                String [] splitted = s.split(" ");
                if (splitted.length == 1){
                    return splitted[0];
                }
                else {
                    for (int i = splitted.length; i > 0; i--){
                        result += splitted[i-1]+ " ";
                    }
                }
            }
            return result;
        }
    }`
    

    Thank to everyone willing to help my undestand this weird behavior :)


  • 0
    R

    Change: String [] splitted = s.split(" ");
    to String [] splitted = s.trim().split("\s+");


Log in to reply
 

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