码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]38. Length of Last Word最后单词长度

时间:2015-10-24 18:59:37      阅读:182      评论:0      收藏: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.

 

解法1:对输入字符串从后往前扫描,先去掉末尾空格得到输入字符串的“真正”end,然后找到第一个空格位置i,两个index之间即为最后一个单词,返回其长度即可。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n = s.size(), end = n - 1;
        int i = n - 1, j = n - 2;
        if (n == 0) return 0;
        for (; i >= 0; --i)
        {
            if (i == n - 1 && s[i] ==  )
            {
                while (s[j] == s[j + 1]) --j;
                if (j < 0) return 0;
                i -= end - j;
                end = j;
            }
            if (s[i] ==  ) return end - i;
        }
        return end - i;
    }
};

 

解法2:另一个思路是先对输入字符串预处理,去掉开头和结尾多余的空格,然后从前往后扫描,遇到空格将计数器置零,否则计数器自增。这样计数器记录的自然就是最后一个单词的长度。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n = s.size(), count = 0;
        int left = 0, right = n - 1;
        while (left < n && s[left] ==  ) ++left;
        while (right >= 0 && s[right] ==  ) --right;
        for (int i = left; i <= right; ++i)
        {
            if (s[i] !=  ) ++count;
            else count = 0;
        }
        return count;
    }
};

 

[LeetCode]38. Length of Last Word最后单词长度

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4907313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!