美文网首页
58. Length of Last Word 最后一个单词的长

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

作者: xingzai | 来源:发表于2021-08-31 00:55 被阅读0次

    题目链接
    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:58. Length of Last Word 最后一个单词的长

          本文链接:https://www.haomeiwen.com/subject/ulpailtx.html