[LintCode] 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.

If the last word does not exist, return 0.

Notice

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

Given s = "Hello World", return 5.

LeetCode上的原题,请参见我之前的博客Length of Last Word

解法一:

class Solution {
public:
    /**
     * @param s A string
     * @return the length of last word
     */
    int lengthOfLastWord(string& s) {
        if (s.empty()) return 0;
        int res = 0;
        if (s[0] != ' ') res = 1;
        for (int i = 1; i < s.size(); ++i) {
            if (s[i] != ' ') {
                if (s[i - 1] == ' ') res = 1;
                else ++res;
            }
        }
        return res;
    }
};

解法二:

class Solution {
public:
    /**
     * @param s A string
     * @return the length of last word
     */
    int lengthOfLastWord(string& s) {
        int tail = s.size() - 1, res = 0;
        while (tail >= 0 && s[tail] == ' ') --tail;
        while (tail >= 0 && s[tail] != ' ' ) {
            --tail;
            ++res;
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:求末尾单词的长度[LintCode] Length of Last Word ,如需转载请自行联系原博主。

相关文章
|
7天前
387.字符串中的第一个唯一字符 —> `size()`
387.字符串中的第一个唯一字符 —> `size()`
LeetCode第58题:最后一个单词的长度
题目 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。如果不存在最后一个单词,请返回 0 。 说明: 一个单词是指由字母组成,但不包含任何空格的字符串。 示例:输入: "Hello World"输出: 5 代码 class Solution: def...
|
Java 索引 Python
LeetCode 151:给定一个字符串,逐个翻转字符串中的每个单词 Reverse Words in a String
公众号:爱写bug(ID:icodebugs) 翻转字符串里的单词 Given an input string, reverse the string word by word. 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
1566 0
|
索引 Python Java
LeetCode 557:反转字符串中的单词 III Reverse Words in a String III
公众号:爱写bug(ID:icodebugs) 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 Given a string, you need to reverse the order of characters in each word within a.
906 0