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.

    Note: A word is defined as a character sequence consists of non-space characters only.

    题解

    关键点在于确定最后一个字符串之前的空格,此外还需要考虑末尾空格这一特殊情况,容易想到的是利用一前一后两个索引记录,最后相减即可。但其实可以巧妙地直接利用非空字符串长度表示。除了通常简单粗暴的方法,我们还可以尝试使用正则表达式这一利器对字符串进行处理。

    Python

    Python

    1. class Solution(object):
    2. def lengthOfLastWord(self, s):
    3. :type s: str
    4. :rtype: int
    5. """
    6. if s is None: return 0
    7. m = re.search(r'(?P<word>\S+)\s*$', s)

    C++

    1. class Solution {
    2. public:
    3. int lengthOfLastWord(string s) {
    4. if (s.empty()) return 0;
    5. int x = s.find_last_not_of(' ');
    6. return (x == std::string::npos) ? 0 : x - s.find_last_of(' ', x);
    7. }

    C++

    1. public class Solution {
    2. public int lengthOfLastWord(String s) {
    3. int len = 0;
    4. for (int i = s.length() - 1; i >= 0; i--) {
    5. if (s.charAt(i) == ' ') {
    6. if (len > 0) return len;
    7. } else {
    8. len++;
    9. }
    10. }
    11. return len;

    源码分析

    复杂度分析

    遍历一次,时间复杂度 O(n),不复制源字符串,空间复杂度 O(1).