How about this solution


  • 0
    Y
    public int lengthOfLastWord(String s) {
    
            int sind = s.lastIndexOf(" ");
            int len = s.length();
            if (sind == len-1) {
                return lengthOfLastWord(s.substring(0,sind));
            }
            return  len-sind-1;
    }
    

    it works...


  • 0
    Y
    if(s==null){
        return 0;
    }
    s = s.trim();
    int sind = s.lastIndexOf(" ");
    int len = s.length();
    return  len-sind-1;
    

Log in to reply
 

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