[LeetCode] Length of Last Word 字符串查找

时间:2023-03-09 15:21:00
[LeetCode] 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.

Hide Tags

String


    这题比较简单,只是可能前面有空格,后面有空格。- -
算法逻辑:
  1. 排除最后的空格
  2. index 从后往前查第一个空格。
  3. 返回长度。
 #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 ;
}