Leetcode NO.58 Length of Last Word

来源:互联网 发布:python 数值计算精度 编辑:程序博客网 时间:2024/04/25 22:39

本题题目要求如下:

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.

本题难度是easy,一般easy的题,用最直观的思路就可以解出来,我第一次做倒着数第一个空格(出现过字母后)

这次用正着数,就是全遍历一遍,遇见空格的话,则停止记数,当然细节方面还要看代码。。

时间复杂度一样,不过理论上第一次的应该要快一些。

代码如下:

class Solution {public:    int lengthOfLastWord(string s) {        int cnt = 0;        for (int i = s.length() - 1; i >= 0; --i) {            if (s[i] != ' ') {                ++cnt;            }            else if (cnt != 0) {                break;            }        }        return cnt;    }};




0 0
原创粉丝点击