58. Length of Last Word

Problem:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

思路

Solution (C++):

int lengthOfLastWord(string s) {
    if (s.empty())  return 0;
    int len = s.length(), count = 0, i;
    vector<int> vec;
    vec.push_back(-1);
    for (i = 0; i < len; ++i) {
        if (s[i] == ' ')  vec.push_back(i);
    }
    vec.push_back(len);
    int n = vec.size();
    for (int j = n-1; j > 0; --j) {
        if (vec[j] - vec[j-1] > 1)  { count = vec[j] - vec[j-1] - 1;  break; }
    }
    return count;
}

性能

Runtime: 4 ms  Memory Usage: 6.8 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12584754.html