思路:
自动机, 每次输入一个空格, 就进行一次状态转换
逆序遍历的效果应该会更好, 不过我就是简单的正序遍历了下练练自动机
代码:
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int len;
void countWord(const char *s, int &i, const int &n) {
len = 0;
while(s[i] != ' ' && i < n) {
len++;
i++;
}
}
int lengthOfLastWord(const char *s) {
len = 0;
int size = strlen(s);
for(int i = 0; i < size; i ++) {
while(s[i] == ' ')
i++;
if(i != size)
countWord(s, i, size);
}
return len;
}
};