Issue with test case "a"


  • 0
    C

    My solution gives me the correct answer 1 when I run it locally on my machine but the OJ gives 0, so I am confused.

    public int lengthOfLastWord(String s) {
            int len = s.length(), i = 0, count = 0;
            if(len == 0) return 0;
            for(i = len - 1; i >= 0; --i) {
                if(s.charAt(i) == ' ') break;
                count++;
            }
            return count;
        }

  • 0
    C

    Your code is not skipping trailing spaces in the string. It failed at test-case 38 where string is "a " with a trailing space. Following is the modified code which passes the test.

        int len = s.length();
        if(len == 0) 
            return 0;
        int i = len-1, count = 0;
        while (s.charAt(i)==' ') --i; // skip trailing spaces
        for(; i >= 0; --i) {
            if(s.charAt(i) == ' ') break;
            count++;
        }
        return count;
    

    [Note: I haven't tested this on Java. I converted C++ => Java hope you get the idea. ]


  • 0
    C

    Thank you, I didn't realize the test case is "a " instead of "a", lol
    BTW, your code would be perfectly fine as java with only a little change. "while (s.charAt(i)==' ') --i;" -> " while (i >= 0 && s.charAt(i)==' ') --i;".
    Thanks again for your precious time!


Log in to reply
 

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