Java solution


  • 1
    T
    public int lengthOfLastWord(String s) {
      if (s == null || s.trim().length() == 0) {
        return 0;
      }
    
      String[] words = s.split(" ");
      return words[words.length - 1].length();
    }
    

  • 0
    P
    import java.util.*;
    
    class Solution {
        public int lengthOfLastWord(String s) {
            if ((!(s.trim().length() > 0)) || (s == null)) {
                return 0;
            }
            String[] splitStr = s.split("\\s+");
            return splitStr[splitStr.length-1].length();
        }
    }
    

  • 0
    T

    @praneeth98 can cause NPE if "s" is null, "s == null" should be the first check. Also, "!(s.trim().length > 0)" is essentially same as "s.trim().length() == 0" as the length can never be < 0


Log in to reply
 

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