---
# System prepended metadata

title: LeetCode 58. Length of Last Word
tags: [Leetcode]

---

---
title: 'LeetCode 58. Length of Last Word'
disqus: hackmd
---

# LeetCode 58. Length of Last Word



## Description

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

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

## Example

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

## Constraints

1 <= s.length <= 10^4^
s consists of only English letters and spaces ' '.
There will be at least one word in s.

## Answer

抓出最後一個子字串的長度，就直接將s+len-1移到字串尾，然後倒著找第一個子字串來計算答案。先用空格找出第一個有字的地方之後才能開始找空格。指標寫法，可用memory address大小來當邊界。

```Cin=
//2022_03_29
int lengthOfLastWord(char * s){
    int cnt = 0, len = strlen(s);
    char *end = s + len - 1;
    while(end >= s && *end == ' '){end--;}
    while(end >= s && *end != ' '){cnt++;end--;}
    return cnt;
}
```



## Link
https://leetcode.com/problems/length-of-last-word/
###### tags: `Leetcode` 
