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;
        }
    };
  • 相关阅读:
    数据库ACID
    tcp ip detatils
    process vs thread
    C++ virtual descructor
    static_cast dynamic_cast const_cast reinterpret_cast总结对比
    Meta Programming
    C++ traits
    c++内存管理
    洛谷 P4136 谁能赢呢?
    洛谷 P1166 打保龄球
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4097531.html
Copyright © 2011-2022 走看看