Description
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"
,
return5
.
Analysis
Better use the function in class string
:
//Find character `c` from the positon `npos` to the beginning of string `s`.
//return the right position when succeeded
//return string::npos when failed
int rfind(char c, int pos = npos) const;
Code
class Solution {
public:
int lengthOfLastWord(string s) {
if (s == "") return 0;
int lastpos = s.size() - 1;
while (s[lastpos] == ' ') lastpos--;
if (lastpos < 0) return 0;
int find = s.rfind(' ', lastpos);
return (find == lastpos)?(lastpos + 1):(lastpos - find);
}
};
Appendix
- Link: https://leetcode.com/problems/length-of-last-word/
- Run Time: 3ms