leetcode Reverse Words in a String

来源:互联网 发布:php 解析html 编辑:程序博客网 时间:2024/05/19 16:47

原题链接:https://leetcode.com/problems/reverse-words-in-a-string/

Description

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

class Solution {public:    void reverseWords(string &s) {        n = s.length();        string x = "";        reverse(s.begin(), s.end());        while (!op.empty()) op.pop();        for (size_t i = 0; i < n;) {            while (i < n && s[i] == ' ') i++;            if (i == n) break;            while (i < n && s[i] != ' ') { op.push(s[i++]); }            while (!op.empty()) { x += op.top(); op.pop(); }            x += ' ';        }        if (x.length()) x.pop_back();        s = x;    }private:    size_t n;    stack<char> op;};
0 0
原创粉丝点击