[LeetCode 58] 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
.
DiffcultyEasy
Similar Problems
Analysis
// 从后往前扫描 唯一的细节就是要去掉尾部的空格,然后读到下一个空格,记录下长度。 时间复杂度是O(n),空间复杂度是O(1)。
class Solution { public: int lengthOfLastWord(string s) { if(s.empty()) return 0; int idx = s.length() - 1; while(idx >= 0 && s[idx] == ' ') idx--; // !isalpha(s[idx]) int idx2 = idx; while(idx2 >= 0 && s[idx2] != ' ') idx2--; return idx - idx2; } };
// 从前往后扫描 用两个变量lastLen, curLen分别记录前一个和当前word的长度。
- 当前字符为字母时,说明当前word仍然没结束,更新curLen++
- 当前字符为空格时,如果curLen不为0,说明是一个word刚结束,将lastLen更新为curLen。
- 当前字符为空格且curLen=0,说明前一个字符也是空格,不需要额外操作。
- 由于只有在遇到空格时才更新lastLen,当最后一个word后没有空格就结束时,
lastLen还没有被更新,所以在搜索完整个s后,如果curLen不为0,
则curLen才是真正最后word的长度。而如果最后一个word后有空格,则lastLen为长度。
class Solution {
public:
int lengthOfLastWord(const char *s) {
} };int lastLen = 0, curLen = 0; while(*s) { if(isalpha(*s)) curLen++; else if(curLen!=0) { lastLen = curLen; curLen = 0; } s++; } return curLen==0? lastLen : curLen;