[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.

【解题思路】

这道题其实很简单,只要换个角度从右边开始扫描,分别找到最后一个word的开端和结尾的位置就可以了,但因为一些细节上的问题wa了好几次,考虑的还是不全面。

要注意的是:1、可能最后一个word的右边还有空格 2、会出现全是空格的情况。

【代码】

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len=s.size();
        int pos=len-1;
        int i;
        if(len==0) return 0;
        for(i=len-1;i>=0;i--){
            if(s[i]!=' '){
                pos=i;
                break;
            }
        }
        for(i=pos;i>=0;i--){
            if(s[i]==' '){
                break;
            }
        }
        return pos-i;
    }
};

我的ac代码耗时是4ms,在discuss里看到有人是0ms,思路是一样的,主要是将for循环改成了while循环,while循环因为比for循环少了一步,所以速度会更快一点。

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、付费专栏及课程。

余额充值