Leetcode P0058"Length of Last Word" 题解

2020/08/27 Leetcode

博文中会简要介绍Leetcode P0058题目分析及解题思路。

“Length of Last Word”是一道简单题,思路就是从右往左找到连续的字母串即可。

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.

以下是Java的题解代码实现。

class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null || s.length() == 0)
            return 0;
        
        int validEnd = s.length()-1;
        while (validEnd >= 0 && s.charAt(validEnd) == ' ')
            --validEnd;
        
        int len = 0;
        while (validEnd >= 0 && s.charAt(validEnd) != ' ') {
            ++len;
            --validEnd;
        }
        
        return len;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int lengthOfLastWord(string s) {
        if (s.length() == 0)
            return 0;
        
        int valid_end = s.length()-1;
        while (valid_end >= 0 && s[valid_end] == ' ')
            --valid_end;
        
        int len = 0;
        while (valid_end >= 0 && s[valid_end] != ' ') {
            --valid_end;
            ++len;
        }
        
        return len;
    }
};

Search

    Table of Contents