题解 | #统计字符#

字符串最后一个单词的长度

http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

#include <iostream>
#include <string>

class Solution {
    private:
    static bool isSep(int ch) {
        return ch == '\r' || ch == '\n' || ch=='\t' || ch == ' ';
    }
    static std::string getWord(const std::string s, size_t len, size_t &i) {
        std::string word = "";
        int ch = 0;
        // 跳过空白
        for (; i < len && (ch = s.at(i)); i++) {
            if (!isSep(ch)) {
                break;
            }
        }
        for (; i < len && (ch = s.at(i)); i++) {
            if (isSep(ch)) {
                break;
            }
            word.append(1, ch);
        }
        return word;
    }
    public:
    size_t lenOfLastWord(const std::string s) {
        std::string thisWord, lastWord = "";
        size_t len = s.size();
        for(size_t i = 0; ;lastWord = thisWord) {
            thisWord = getWord(s, len, i);
            if (thisWord.size() < 1) {
                break;
            }
        }
        return lastWord.length();
    }
};

int main(int argc, char *argv[]) {
    std::string s;
    std::getline(std::cin, s);
    
    Solution solution;
    std::cout << solution.lenOfLastWord(s) << std::endl;
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
轻絵梨花泪沾衣:南泵,大少爷驾到通通闪开
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务