[leetcode 58] Length of Last Word

来源:互联网 发布:windows8装mac 编辑:程序博客网 时间:2024/06/06 02:08

Question:

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.


分析:

1、如果S长度为0,直接返回0即可;

2、如果s全是“ ”,也是直接返回0;

3、如果s中没有“ ”,则直接返回s的长度即可;

4、如果s中有“ ”,则将s以“ ”分词,将最后一个词的长度返回即可。


<span style="font-size:14px;">class Solution {private:    vector<string> split(string s, string pattern){        int pos;        vector<string> result;        s += pattern;        for(int i = 0; i < s.size(); ++i){            pos = s.find(pattern,i);            if(pos < s.size() && pos != i){                string sub = s.substr(i,pos-i);                result.push_back(sub);                i = pos + pattern.size()-1;            }        }        return result;    }public:    int lengthOfLastWord(string s) {         if(s.length() == 0)            return 0;        int i;        for( i = 0; i < s.size(); i++){            if(s[i] != ' ')                break;        }        if(i == s.size())            return 0;        if(s.find(" ",0) != string::npos){            vector<string> st;            st = split(s," ");            return st[st.size()-1].length();        }        else            return s.length();    }};</span>


0 0
原创粉丝点击