LeeCode from 0 ——58. Length of Last Word
阿新 • • 發佈:2018-06-22
n-1 循環 from num defined pty cte def str
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.
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