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.

解题思路:

开始的思路(不严谨):

        遍历整个s,若当前字符不为空格(' '),则count++;否则,令count=0,再重来。

开始的C程序(未通过):

<span style="font-size:12px;">int lengthOfLastWord(char* s) {
    int count=0;
    int len=strlen(s);
    if(len==0) count=0;
    else {
        for(int i=0; i<len; i++){
            if(s[i]!=' ') count++;
            else count=1;
        }
    }
    return count;
}</span>

错误原因:

        测试的时候发现如下测试用例通不过(为了方便看,下例中用 ~ 表示空格):

                 "a~~b"     "a~"     "a~~"     "~a"     "~~~"   等

        后来发现未考虑“有多个空格”、“以空格结尾”、“以空格开头”等问题。

更新思路:

    1. 当遇到空格后,先继续遍历到空格结束,因为可能会有多个空格连着出现;

    2. 注:当前字符不为空格时,令count=1,而不是count=0


C程序实现(通过):

int lengthOfLastWord(char* s) {
    int count=0;
    int len=strlen(s);
    if(len==0) count=0;
    else {
        for(int i=0; i<len; i++){
            if(s[i]!=' ') count++;
            else {
                while(s[i]==' ') i++;
                if(s[i]=='\0') ;
                else count=1;
            }
        }
    }
    return count;
}


别人的程序(引用):

我用的是数组实现,在讨论组里看到了别人的指针实现,很简洁巧妙,搬来看看:

int lengthOfLastWord(char* s) {
  int lastLen = 0;
  char* p = s + strlen(s) -1;
  while(p>=s && isspace(*p)) p--;
  while(p>=s && !isspace(*(p--))) lastLen++;
  return lastLen;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值