[LeetCode] 58. Length of Last Word

题目链接:传送门

Description

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.

Example:

Input: "Hello World"
Output: 5

Solution

题意:

对于给定的只包含大小写字母和空格的字符串,求出最后一个单词的长度

思路:

一开始去判空格的位置还是踩了很多坑(特殊情况要考虑全,后来就用字符串直接做

class Solution {
public:
    int lengthOfLastWord(string s) {
        string res = "", tmp = "";
        for (int i = 0; i < s.length(); i++) {
            if (s[i] != ' ') {
                tmp += s[i];
            } else {
                if (tmp != "")  res = tmp;
                tmp = "";
            }
        }
        if (tmp != "")  res = tmp;
        return res.length();
    }
};

补充:

Discuss 里面有很多可供借鉴的写法,譬如:

(1) 7-lines 4ms C++ Solution

class Solution {
public:
    int lengthOfLastWord(string s) { 
        int len = 0, tail = s.length() - 1;
        while (tail >= 0 && s[tail] == ' ') tail--;
        while (tail >= 0 && s[tail] != ' ') {
            len++;
            tail--;
        }
        return len;
    }
};
posted @ 2018-02-23 02:22  酒晓语令  阅读(105)  评论(0编辑  收藏  举报