题目链接: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.
这道题的要求是返回字符串中最后一个单词的长度。
遍历字符串,统计单词长度。只有一点需要注意,就是最后单词后面有空格的情况,因此需要判断下一字符是否是字母,如果是,这重置长度为0即可。
时间复杂度:O(n)
空间复杂度:O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution
{
public:
int lengthOfLastWord(const char *s)
{
int l = 0;
while(*s)
{
if(' ' != *s ++)
++ l;
else if(*s && ' ' != *s)
l = 0;
}
return l;
}
};
当然,也可以引入计数器遍历cnt用于记录当前单词长度,只有当cnt加1的时候,更新结果变量res。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution
{
public:
int lengthOfLastWord(const char *s)
{
int res = 0, cnt = 0;
while(*s)
{
if(' ' == *s ++)
cnt = 0;
else
res = ++ cnt;
}
return res;
}
};