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

    解法1:对输入字符串从后往前扫描,先去掉末尾空格得到输入字符串的“真正”end,然后找到第一个空格位置i,两个index之间即为最后一个单词,返回其长度即可。

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n = s.size(), end = n - 1;
            int i = n - 1, j = n - 2;
            if (n == 0) return 0;
            for (; i >= 0; --i)
            {
                if (i == n - 1 && s[i] == ' ')
                {
                    while (s[j] == s[j + 1]) --j;
                    if (j < 0) return 0;
                    i -= end - j;
                    end = j;
                }
                if (s[i] == ' ') return end - i;
            }
            return end - i;
        }
    };

    解法2:另一个思路是先对输入字符串预处理,去掉开头和结尾多余的空格,然后从前往后扫描,遇到空格将计数器置零,否则计数器自增。这样计数器记录的自然就是最后一个单词的长度。

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n = s.size(), count = 0;
            int left = 0, right = n - 1;
            while (left < n && s[left] == ' ') ++left;
            while (right >= 0 && s[right] == ' ') --right;
            for (int i = left; i <= right; ++i)
            {
                if (s[i] != ' ') ++count;
                else count = 0;
            }
            return count;
        }
    };
  • 相关阅读:
    微信证书发布涉及到的问题
    C# Timer自带定时器
    微信accesstoken回调
    c#数组乱序,打乱数组
    JS 数组乱序
    百度地图LBS开放平台AK一直没有用
    C# 微信支付证书使用
    提交失败问题一:检测到有潜在危险
    apache如何发布地图服务
    Java后端进阶教程
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4907313.html
Copyright © 2011-2022 走看看