【leetcode】58. Length of Last Word 字符串的末尾词的长度

1. 题目

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.

2. 思路

无聊的题目

3. 代码

class Solution {
public:
    int lengthOfLastWord(string s) {
        int cnt = 0;
        int i = s.length() - 1;
        while (i>= 0 && s[i] == ' ') i--;
        while (i >= 0 && s[i] != ' ') {
            cnt++;
            i--;
        }
        return cnt;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007365291
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞