My Java solution


  • 0
    L
    public class Solution {
    public int lengthOfLastWord(String s) {
        if(s == null || s.length() == 0)
        {
            return 0;
        }
        
        String temp = "";
    
        for(String sub : s.split("\\W+"))
        {
            temp = sub;
        }
        
        return temp.length();
    }

  • 0
    C

    I did mine somewhat the same way but rather than iterating through the split, I just pulled the last element out. I think your way is a bit better than mine in an actual interview because you show off regex and rely slightly less on built in libraries.

    public int lengthOfLastWord(String s) {
        String[] split = s.split(" ");
        return s.trim().equals("") ? 0 : split[split.length-1].length();
    }
    

  • 0
    X

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


Log in to reply
 

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