leetcode -58. 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.

题目分析

题目要求求一字符串最后一个单词的长度(字符串由大小字母和空格组成),如果不存在最后一个单词,则返回0。

注意:单词是指仅有非空字符组成字符序列

s="Hello world   "
return 5.

字符串s中world 后有若干空格,但空格并不属于单词,因此s中最后一个单词是指world。

解题思路

题目中要求最后一个单词的长度,即字符串s从后边开始,从第一非空字符开始查找空格,空格所在位置与第一个非空字符位置索引差即为最后一个单词的长度。如上例中字符串s,字符d所在位置索引与Hellow 和world之间的空格所在位置索引之差即为单词world的长度。

代码


#include <stdio.h>
#include <string.h>

int lengthOfLastWord(char* s) {

    int l=strlen(s);           //字符串长度
    printf("l=%d",l);          
    int i,j=0;

    if (l==0)                  //空字符串
        return 0;

    for(i=l;i>0;i--)           //第一个非空字符所在位置
    {
        if(*(s+i-1)!=32)       //当字符串由空格组成时,查找到最后一个字符时i=1,i--后等于零结束循环
           break;
    }
    printf("i=%d",i);

    if(i==0)                  //若找不到第一个非空字符,即字符串由若干空格组成
        return 0;

    for(j=i-1;j>0;j--)        //查找非空字符前边的第一个空格,当字符串中只有一个单词时,即j=1时仍未找到空格,
                              //j--等于零,结束循环
    {
        if(*(s+j-1)==32)
            break;
    }

   return i-j;

}

int main ()
{
    char *strs="a  a    ";

    int llw,i=0;
    int size=strlen(strs);
    printf("size=%d\n",size);
    llw=lengthOfLastWord(strs);
    printf("size=%d\n",size);

    printf("%c\n",*(strs+size-1));

    printf("llw=%d\n",llw);

    return 0;
}

参考文献
[1] http://shmilyaw-hotmail-com.iteye.com/blog/2293842

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值