58. Length of Last Word

来源:互联网 发布:淘宝沫沫运动是正品么 编辑:程序博客网 时间:2024/05/21 15:01

58. 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.

Analysis:
题目不难,但是要细心做。
单元测试用例确实很重要啊,以后需要学习的。
Source Code(C++):

#include <iostream>#include <string>#include <map>#include <vector>using namespace std;class Solution {public:    int lengthOfLastWord(string s) {        if (s.empty()) {            return 0;        }        else {            int tail_index = s.size()-1;            while(s.at(tail_index) == ' ') {   //去除尾部的' '                tail_index--;                if (tail_index<0){  //有可能字符串只有' '组成                    return 0;                }            }            int last_index = tail_index;            while(s.at(tail_index) !=' ') {                tail_index--;                if (tail_index<0){      //有可能字符串只含一个word                    break;                }            }            return last_index-tail_index;        }    }};int main() {    Solution sol;    cout << sol.lengthOfLastWord("H ");    return 0;}
0 0
原创粉丝点击