[leetcode] 反转字符串中的单词

151. 反转字符串中的单词 - 力扣(LeetCode)

解题思路:反向遍历,利用双指针截取

cpp 复制代码
class Solution {
public:
    string reverseWords(string s) {
        string ret;
        //先去掉尾部的空格字符
        int index = s.size() - 1;
        while(s[index] == ' ') index--;
        int n = index;
        while(index >= 0){
            //index >= 0 处理边界情况不能越界
            while(index >= 0 && s[index] != ' ') index--; //遇到空格停止
            ret += s.substr(index + 1, n - index) + ' ';
            //处理中间的空格
            while(index >= 0 && s[index] == ' ') index--;
            n = index; //更新n,以便后续确认新单词的长度
        }
        //处理最后多出来的空格
        ret.erase(ret.end() - 1);

        return ret;
    }
};