leetcode 58 求一个包含空格的字符串中最后一个字符串的长度

来源:互联网 发布:新开淘宝店没生意 编辑:程序博客网 时间:2024/05/20 09:24
方法一:倒着找空格,并计算空格出现的个数。
class Solution {public:    int lengthOfLastWord(string s) {        int len = s.length(), index = -1, lastposition = len-1,cnt=0;    string sep = " ";    while(lastposition!=-1&&-1!=(index=s.find_last_of(sep,lastposition))){        if(index==lastposition){            lastposition--;            cnt++;        }        else{            return len-index-1-cnt;        }    }    if(lastposition==-1){        return 0;    }    return len-cnt;    }};
方法二:顺着找,并及时擦除前面的字符串。
<pre name="code" class="cpp">class Solution {public:    int lengthOfLastWord(string s) {        int len=0;        int pos;        while (s.length()!=0){            pos = s.find(" ");            if (pos==string::npos)                return s.length();            else{                if (pos!=0)                    len = pos;                s.erase(0,pos+1);            }        }        return len;    }};


                                             
0 0
原创粉丝点击