Java solution using substring, trim, lastIndexOf


  • 2
    A
    public int lengthOfLastWord(String s) {
        if (s == null || s.equals("")) {
            return 0;
        }
        s = s.trim();
    
        int index = s.lastIndexOf(' ');
        if (index < 0) {
            return  s.length();
        } else {
            String sub = s.substring(index + 1);
            return sub.length();
        }
    }

  • 0
    Y

    One quick point, the second condition s == "" in your first if worth nothing as the equality of two strings should be checked with s.equals("")


  • 0
    Q

    Are you familiar with String interning?


  • 0
    A

    Good catch. Thanks.


Log in to reply
 

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