zoukankan      html  css  js  c++  java
  • HappyLeetcode35: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.

    这道题真是费了九牛二虎之力,本来没有多难的题目,自己本来对这道题感觉确实挺简单的。但是很多情况没有考虑周全,导致代码频繁出现bug。最后终于调试通过了

    我的代码:

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            if (strlen(s) == 0)
                return 0;
            int length = strlen(s);
            int count = 0;
            while (length - count - 1>=0)
            {
                if ((s[length - count - 1] >= 'a' && s[length - count - 1] <= 'z' || s[length - count - 1] >= 'A'&&s[length - count - 1] <= 'Z') && length - count - 1 >= 0)
                {
                    count++;
                    if (length - count  == 0 || s[length - count - 1] == ' ')
                        break;
                }
                    
                if (s[length - count - 1] == ' ')
                {
                    length --;
                    continue;
                }
                    
            }
            return count;
        }
    };

    在参考别人的代码,真是感觉自愧不如啊。下面的这种解法,又简单又直观

    int lengthOfLastWord(const char* s) {
            int len = 0;
            while (*s) {
                if (*s++ != ' ')
                    ++len;
                else if (*s && *s != ' ')
                    len = 0;
    
            }
            return len;
        }
  • 相关阅读:
    为什么Redis比Memcached易
    请注意CSDN社区微通道,许多其他的精彩等着你
    采用ACE登录设施(一)HelloWorld
    AIX 7.1 install python
    spring mvc入门
    iOS开展——全球应对MotionEvent
    2015第35周日
    2015第35周六转相见恨晚的知识列表
    2015第35周五JavaScript变量
    2015第35周四
  • 原文地址:https://www.cnblogs.com/chengxuyuanxiaowang/p/4189233.html
Copyright © 2011-2022 走看看