zoukankan      html  css  js  c++  java
  • 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.

    C++代码实现:

    #include<iostream>
    #include<vector>
    #include<string>
    #include<sstream>
    #include<cstring>
    using namespace std;
    
    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            istringstream istr(s);
            vector<string> vec;
            string ss;
            while(istr>>ss)
                vec.push_back(ss);
            if(vec.size()==0)
                return 0;
            return vec[vec.size()-1].length();
        }
    };
    
    int main()
    {
        const char *s = "Hello World";
        Solution ss;
        cout<<ss.lengthOfLastWord(s)<<endl;
    }

    本来是很简单的一个题,但是因为没有判断字符串全部由空格组成。这时经过istringstream处理之后压入到vector中的元素将是0个,因此vec.size()将是0,所以最后一个将返回运行时错误。(细节决定成败啊)

     以前怎么想到那么麻烦的方法呢,明明用双指针就可以搞定的事啊。。

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            if(s==NULL)
                return 0;
            int len=0;
            const char *p=s;
            const char *q=NULL;
            while(*p!='') ++p;
            p--;
            while(p>=s&&*p==' ') --p;
            if(p<s)
                return 0;
            q=p;
            while(q>=s&&*q!=' ') q--;
            len=p-q;
            return len;
        }
    };
  • 相关阅读:
    WCF 入门例子
    C#傻瓜日志类
    ajax长链接拉实现
    linux命令备忘
    .Net 并发异步处理总结
    grafana初始化密码(转载)
    Android 调用照相机拍照
    自定义android控件EditText 自定义边框 背景
    JSON 请求的实现过程
    [转]Android开发教程:shape和selector的结合使用
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4097531.html
Copyright © 2011-2022 走看看