zoukankan      html  css  js  c++  java
  • Leetcode题解(5):L58/Length of Last Word

    L58: 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.

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

    For example,
    Given s = “Hello World”,
    return 5.

    解题思路:遇到非’ ‘字符,用一个符号表示word開始,遇到’ ‘表示word结束,注意边界情况处理
    优化:能够从字符串末尾開始处理

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int strLen = s.length();
            if(strLen == 0)
                return 0;
    
            int begin = 0;
            int end = 0;
            int pos = 0;
            bool word_start = false;
            while(pos < strLen)
            {
                if(s[pos] != ' ' && !word_start) 
                {
                    begin = pos;
                    word_start = true;
                }
                else if(s[pos] == ' ' && word_start)
                {
                    end = pos;
                    word_start = false;
                }
                pos++;
            }
            if (word_start && pos == strLen)
                end = strLen;
            return end - begin;
        }
    };
  • 相关阅读:
    C#创建线程
    Halcon算子
    二叉树的层次遍历
    反转单链表
    “开-闭”原则 (Open-Closed principle, OCP)
    CSUOJ1867 John and Health rate
    LOCAL_MODULE_TAGS
    void * kmalloc(size_t size, int flags)
    printk(Loglevels string)
    container_of宏定义解析
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7120079.html
Copyright © 2011-2022 走看看