• 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;
        }
    };
  • 相关阅读:
    UVA 1025 A Spy in the Metro DP水题
    ZOJ 3814 Sawtooth Puzzle BFS
    ZOJ 3816 Generalized Palindromic Number
    UVA 10859 Placing Lampposts 树形DP
    UVA 11825 Hackers' Crackdown 状压DP
    POJ 2887 Big String 线段树 离线处理
    POJ 1635 Subway tree systems Hash法判断有根树是否同构
    BZOJ 3110 k大数查询 & 树套树
    sdoi 2009 & 状态压缩
    来自于2016.2.24的flag
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4097531.html
Copyright © 2020-2023  润新知