String: 58. Length of Last Word

来源:互联网 发布:如何优化dnf非常流畅 编辑:程序博客网 时间:2024/06/03 21:21

    这个题这么简单,但是调了好久,最后直接求结果没调好,无奈申请了一个string存放结果,再返回string的长度。

class Solution {public:    int lengthOfLastWord(string s) {        string result = "";        int i = s.size() - 1;        while(s[i] == ' ' && i >= 0)        {            i--;        }        while(s[i] != ' ' && i >= 0)        {            result = s[i] + result;            i--;        }        cout << result << endl;        return result.size();                }};
    但是看了别人写的,发现自己真是蠢……脑子不会转弯…………不用string当然也可以啊,之前总想着定义一个start一个end,但是发现要分情况讨论start和end,又会产生很多if,又容易出错。应该这样就可以:

class Solution {public:    int lengthOfLastWord(string s) {        int len = 0;        int i = s.size() - 1;        while(s[i] == ' ' && i >= 0)        {            i--;        }        while(s[i] != ' ' && i >= 0)        {            len++;            i--;        }        return len;                }};


原创粉丝点击