58. Length of Last Word 最后一个单词的长度

题目链接
tag:

  • Easy;

question
  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 1:

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

Example 2:

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

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

提示:

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

思路:
  这道题要求我们求字符串最后一个单词的长度,很简单倒序遍历,遇到空格跳过,直到遇到第一个字母,开始计数,再遇到空格就退出即可,代码如下:

class Solution {
public:
    int lengthOfLastWord(string s) {
        if (s.empty()) return 0;
        if (s.size() == 1) return 1;

        int count = 0;
        bool flag = true;
        // 从后面开始,遇到空格就跳过,知道遇到第一个字母,开始计数,再遇到空格就break
        for (int i = s.size() - 1; i >= 0 ; --i) {
            if (s[i] == ' ') {
                if (!flag)
                    break;
            }
            else {
                ++count;
                flag = false;
            } 
        }
        return count;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容