1. 程式人生 > >LeetCode 58 Length of Last Word(最後單詞的長度)

LeetCode 58 Length of Last Word(最後單詞的長度)

翻譯

給定一個包含大小寫字母和空格字元的字串,

返回該字串中最後一個單詞的長度。

如果最後一個單詞不存在,返回0。

批註:
一個單詞被定義為包含非空字元的字元序列。

例如,
給定 S = "Hello World",
返回 5

原文

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 

return the length of last word in the string.

If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5.

分析

靈活使用find函式套裝……

這裡寫圖片描述

int lengthOfLastWord(string s) {
    int index = s.find_last_not_of(' ');
    return index == -1 ? 0 : index - s.find_last_of(' ', index
); }