AC short Java solution


  • 3
    X

    public class Solution {

    public int lengthOfLastWord(String s) {
        String array[] = s.split(" ");
        if (array.length == 0)
            return 0;
        else
            return array[array.length - 1].length();
    }
    

    }


  • 0
    E

    This won't work for inputs like "a " where there is empty space at the end. You need to trim s first => String array[] = s.trim().split(" ");


  • 0
    X

    if you input "a ", the expect answer is the same as my output. So there is no problem.


  • 0
    H

    there might be runtime error if s == null


Log in to reply
 

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