Leetcode Length of Last Word

来源:互联网 发布:mac怎么输入大写字母 编辑:程序博客网 时间:2024/09/21 06:19

一开始以为如果最后一个字符是space就不存在最后一个单词,WA了一次。

遍历该string,cnt记录当前单词的长度,如果遇到space,还要判断它的下一个字符是不是space,是的话就重置cnt为0,否则不变。

class Solution {public:    int lengthOfLastWord(const char *s) {        int len = strlen(s);        int cnt = 0;        for(int i = 0; i < len; i++){            if(s[i] == ' ' && i != len-1 && s[i+1] != ' '){                cnt = 0;            }            else if(s[i] != ' '){                cnt++;            }        }        return cnt;    }};

原创粉丝点击