leetcode58. Length of Last Word

来源:互联网 发布:自救手环 淘宝 编辑:程序博客网 时间:2024/06/07 02:19

不知为什么我的博客也会多了些关注,非常感谢能给你们提供到帮助。

让我坚持做的一点事情也有了点意义。



就是判断最后一个字符串的长度。

有一个坑就是最后一个可能为空格,所以要去掉最后的空格。

class Solution {public:    int lengthOfLastWord(string s) {        int n=s.size();        int ans=0;        int i=n-1;        while(s[i]==' ') i--;        for(;i>=0;i--){            if(s[i]>='A'&&s[i]<='Z'||s[i]>='a'&&s[i]<='z') ans++;            if(s[i]==' ') break;        }        return ans;    }};