LeetCode算法解题集:Length of Last Wor

2021-10-19  本文已影响0人  海阔天空的博客

题目:

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.

思路:
思路一,使用string::rfind找最后一个出现的空格,这种方式太复杂,要考虑空格出现的规律,所以第一次使用该算法后,直接抛弃了。
思路二,对非空格的字符计数,遇到空格且遇到下一个字符时候,重新计数。算法复杂度O(n).

代码:

class Solution
{
public:
    int lengthOfLastWord(string s)
    {
        int nLastWordLen = 0;
        int bFindSpace = false;
        for (size_t i = 0; i < s.size(); i++)
        {
            if (s[i] == ' ')
            {
                bFindSpace = true;
                continue;
            }
 
            if (bFindSpace)
            {
                nLastWordLen = 0;
                bFindSpace = false;
            }
 
            nLastWordLen++;
        }
 
        return nLastWordLen;
    }
};

总结:
再简单的题目还是要靠思路,思路决定出路,思路错了,原地打转,出不了迷宫!

本文摘录于海阔天空的博客,作者: zjg555543,发布时间: 2015-09-09

上一篇下一篇

猜你喜欢

热点阅读