版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32360995/article/details/86777117
题目:
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.
Example:
Input: "Hello World" Output: 5
题意:
找出字符串中最后一个单词的长度
思路:
从后往前找,cnt计数,遇到空格判断cnt的值,不为0说明已经算出最后一个单词的长度,返回cnt~一道水题大佬们怎么做的时间复杂度那么低,你们是魔鬼吗?服了,膜拜~Runtime: 8 ms, faster than 4.66% of C++ online submissions for Length of Last Word.
Code:
class Solution {
public:
int lengthOfLastWord(string s) {
int cnt=0,i=s.size()-1;
for(;i>=0;i--){
if(s[i]!=' ') cnt++;
else{
if(cnt) return cnt;
}
}
return cnt;
}
};