Leetcode(58)题解:Length of Last Word

时间:2023-03-09 08:00:30
Leetcode(58)题解:Length of Last Word

https://leetcode.com/problems/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.

思路:

主要是确定最后一个单词的边界。注意特殊情况。

AC代码:

 class Solution {
public:
int lengthOfLastWord(string s) {
int begin=-,end=-,j,n=s.size();
for(j=n-;j>=;j--)
if(s[j]!=' '){
begin=j;
break;
}
if(begin==-)
return ;
for(j=begin;j>=;j--){
if(s[j]==' '){
end=j+;
break;
}
}
if(end==-)
end=;
return begin-end+;
}
};