• 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;
        }
    };
  • 相关阅读:
    【SDOI2014】数表
    【洛谷P4735】最大异或和
    FFT学习笔记
    【SHOI2008】堵塞的交通
    HDU 1754 I Hate It 线段树
    hdu 1166 敌兵布阵 ( 线段树或者树状数组)
    hdu 5339 Untitled dfs
    The mook jong
    hdu 5363 Key Set 快速幂
    HDU 1983 Kaitou Kid
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7120079.html
Copyright © 2020-2023  润新知