首页 > 代码库 > leetcode Reverse Words in a String

leetcode Reverse Words in a String

将句子的词反转,例如:

Given s = "the sky is blue",
return "blue is sky the".

思路:就是从后面往前,找到非空格的长度,然后取到另一个串中。遍历一次就可以了。如下:

class Solution {public:    void reverseWords(string &s) {        if (s.size() < 1) return ;        int ind = s.size() - 1, wordLen = 0, tmpind;        string ans = "";        while(ind >=0)        {            wordLen = 0;            while(ind >= 0 && s[ind] ==  ) ind--;            tmpind = ind;            while(ind >= 0 && s[ind] !=  ) ind--;            wordLen = tmpind - ind;            if (wordLen > 0)            {                if (ans.size() == 0)                    ans = s.substr(ind + 1, wordLen);                else                    ans = ans +   + s.substr(ind + 1, wordLen);            }            ind--;        }        s = ans;    }};

这次又出现 unlock the question,然后评分

leetcode Reverse Words in a String