• 【LeetCode】58. Length of Last Word


    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.

    用ret记录上一个单词的长度,用cur记录当前单词的长度。

    每遇到空白符,将cur赋给ret,然后cur置零。

    如果以字母结尾,返回cur

    如果以空格结尾,返回ret(此时cur为0)

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            int ret = 0;
            int cur = 0;
            while(*s != 0)
            {
                while(*s != 0 && *s == ' ')
                    s ++;
                if(*s == 0)
                    return ret;
                    
                while(*s != 0 && *s != ' ')
                {
                    cur ++;
                    s ++;
                }
                
                if(*s == 0)
                    return cur;
                else
                {
                    ret = cur;
                    cur = 0;
                }
            }
        }
    };

  • 相关阅读:
    链表相加
    Unity 摄像机跟随
    整数反转
    两数和
    频繁项集挖掘思路
    有关于二进制的乘法计算(原码一位乘)
    JAVA面向对象(下)
    JAVAAPI
    JAVA面向对象()上)
    JAVA基础第一章
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4157958.html
Copyright © 2020-2023  润新知