Skip to content

LeetCode-tasks/Length-of-Last-Word

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 

Repository files navigation

Length-of-Last-Word

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World" Output: 5

Example 2:

Input: s = " " Output: 0

Constraints:

1 <= s.length <= 10^4

s consists of only English letters and spaces ' '.

Solution in Java

class Solution {
    public int lengthOfLastWord(String s) {
        int l = 0;
        s = s.trim();
        for(int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                l = 0;
            } else {
                l++;
            }
        }
        return l;
    }
}

Solution in JavaScript

var lengthOfLastWord = function(s) {
    let words = s.split(' ');
    let lastWord = words[words.length - 1];
    
    if (words.length > 1 && lastWord.length === 0) {
        words.pop();
        return lengthOfLastWord(words.join(' '));
    }
    
    return lastWord.length;
};

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published