题目链接:传送门

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;
    }
};

相关文章:

  • 2022-01-28
  • 2021-07-04
  • 2021-05-24
  • 2021-08-20
  • 2021-12-06
  • 2021-09-11
猜你喜欢
  • 2021-08-21
  • 2021-08-15
  • 2021-10-30
  • 2021-12-24
  • 2021-05-17
  • 2022-02-08
相关资源
相似解决方案