leetcodeOJ 557. Reverse Words in a String III

来源:互联网 发布:淘宝食品安全怎么填写 编辑:程序博客网 时间:2024/05/16 04:19

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

先按空格把每个word分开,再逆转每个word,

class Solution {public:    string reverseWords(string s) {        string ans = "";        int pos = 0;        int idx = 0;        while((idx = s.find(' ', pos)) != string::npos){            string str = s.substr(pos, idx-pos);            reverse(str.begin(), str.end());            ans += str;            ans += ' ';            pos = idx+1;        }        string str = s.substr(pos);        reverse(str.begin(), str.end());        ans += str;        return ans;    }};

0 0
原创粉丝点击