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;
    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。