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

Leetcode题解(5):L58/Length of Last Word

时间:2015-06-08 17:27:49      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:leetcode   string   

L58: Length of Last Word
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.

解题思路:遇到非’ ‘字符,用一个符号表示word开始,遇到’ ‘表示word结束,注意边界情况处理
优化:可以从字符串末尾开始处理

class Solution {
public:
    int lengthOfLastWord(string s) {
        int strLen = s.length();
        if(strLen == 0)
            return 0;

        int begin = 0;
        int end = 0;
        int pos = 0;
        bool word_start = false;
        while(pos < strLen)
        {
            if(s[pos] != ‘ ‘ && !word_start) 
            {
                begin = pos;
                word_start = true;
            }
            else if(s[pos] == ‘ ‘ && word_start)
            {
                end = pos;
                word_start = false;
            }
            pos++;
        }
        if (word_start && pos == strLen)
            end = strLen;
        return end - begin;
    }
};

Leetcode题解(5):L58/Length of Last Word

标签:leetcode   string   

原文地址:http://blog.csdn.net/kzq_qmi/article/details/46413719

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