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!='\0') ++p; p--; while(p>=s&&*p==' ') --p; if(p<s) return 0; q=p; while(q>=s&&*q!=' ') q--; len=p-q; return len; } };
时间: 2024-10-13 09:36:09