标签:str space 空格 -- 判断 rac cte def nsis
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
解题思路:
1)判断是否以空格结尾,且以末端空格所占位数;
2)从末端非空格位开始,向前循环,非空格位加1,循环到新的空格位则跳出循环。
c++代码如下:
class Solution {
public:
int lengthOfLastWord(string s) {
int n=s.length();
int sum=0;
int nums=0;
for(int j=n-1;j>=0;j--){
if(s[j]==‘ ‘)
nums++;
else
break;
}
for(int i=n-nums-1;i>=0;i--){
if(s[i]!=‘ ‘)
sum++;
else
break;
}
return sum;
}
};
LeeCode from 0 ——58. Length of Last Word
标签:str space 空格 -- 判断 rac cte def nsis
原文地址:https://www.cnblogs.com/ssml/p/9212578.html