![[LeetCode] Length of Last Word 字符串查找 [LeetCode] Length of Last Word 字符串查找](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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
.
Hide Tags
这题比较简单,只是可能前面有空格,后面有空格。- -
算法逻辑:
- 排除最后的空格
- index 从后往前查第一个空格。
- 返回长度。
#include <iostream>
#include <cstring>
using namespace std; class Solution {
public:
int lengthOfLastWord(const char *s) {
int n = strlen(s);
if(n <) return ;
int idx=n-;
while(idx>=&&s[idx]==' ') idx--;
n = idx+;
while(idx>=){
if (s[idx]==' ') break;
idx --;
}
// if(idx<0) return 0;
return n - idx -;
}
}; int main()
{
char s[] = " 12 ";
Solution sol;
cout<<sol.lengthOfLastWord(s)<<endl;
return ;
}