zoukankan      html  css  js  c++  java
  • [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.

     
    Example

    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;
        }
    };
  • 相关阅读:
    (转载)关于一些对location认识的误区
    Python内置数据结构--列表
    Maven
    Python基础语法
    安装ipython和jupyter
    Python环境安装
    Java多线程
    SpringMVC集成springfox-swagger2自动生成接口文档
    SpringMVC拦截器
    SpringMVC异常处理器
  • 原文地址:https://www.cnblogs.com/grandyang/p/5713118.html
Copyright © 2011-2022 走看看