題目: LeetCode - 58. Length of Last Word

題目說明

給一個字串,求字串中最後一個單詞的長度。

解題思路

從後面開始遍歷字串,先使用 String 的 find_last_not_of() 從後往前找第一個字母的 index,接著利用 isalpha() 判斷是否為字母,找出長度即可。

參考解法

1
2
3
4
5
6
7
8
9
class Solution {
public:
int lengthOfLastWord(string s)
{
int idx = s.find_last_not_of(' '), length{};
while(idx >= 0 && isalpha(s[idx--])) ++length;
return length;
}
};