Leetcode笔记整理—easy篇—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.

Example:

Input: "Hello World"
Output: 5

结果:

 结果确实超乎我的意料,可以也是本身题目比较简单,整体的参考价值并不大,算是恢复训练吧[]~( ̄▽ ̄)~*。

源码:

int lengthOfLastWord(char *s)
{
	int len = 0,val = 0,ret = 0;
	len = strlen(s);
	while(s[len] == ' ' || s[len] == 0)
	{
		len--;	
	}
	val = len;
	
	if(s[len] == 0)
	return 0;

	while(s[val] != ' ' && val >= 0)
	{
		val--;
		ret++;
	}
	return ret;
}

至于参考代码,在这里鸣谢大神,这里摘抄只为学习٩(๑❛ᴗ❛๑)۶:

 int lengthOfLastWord(const char* s) {
        int len = 0;
        while (*s) {
            if (*s++ != ' ')
                ++len;
            else if (*s && *s != ' ')
                len = 0;
    
        }
        return len;
    }

分析代码不难发现,除了本质的算法之外,还是尽可能的应用了语法糖来简化书写,同时考虑到本题比较容易,没有太多效率上的限制,所以还是十分优雅的。而且在评论区对于本题的负面评价还是比较多的,认为本题没啥搞头,主要在于对异常的处理;但总体上来讲本题对恢复状态还是很有帮助的ヽ( ̄▽ ̄)ノ。


由于考研的缘故已经一年多没有更新了,今天上号时突然发现有了500多的观看量,感到又惊讶又欣喜,之前以为不会有人看的,所以写的时候也只是为了自我复习,但现在有了全新的动力支撑我继续写下去,谢谢那些曾经关注过我的人,希望我的文章能对你们有所帮助٩(๑>◡<๑)۶。

猜你喜欢

转载自blog.csdn.net/fair_angle/article/details/85541442