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;
        }
    };
  • 相关阅读:
    详解并发和并行意义
    MoleHill Getting Started AGAL(转)
    解决setInterval计时器不准的问题
    Flash视频播放器开发经验总结
    利用pushState开发无刷页面切换
    用小乐图客抓取人人网照片
    如何在Flash中新窗口打开页面而不被拦截
    响应式开发总结
    用Asroute解决复杂状态切换问题
    对iframe跨域通信的封装
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4907313.html
Copyright © 2011-2022 走看看