[LeetCode] 557. Reverse Words in a String III

来源:互联网 发布:淘宝客 traceid 编辑:程序博客网 时间:2024/06/07 02:53

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.
class Solution {public:    string reverseWords(string s) {        string res, word;        istringstream is(s);        while (is >> word) {            for (int i = 0, j = (int)word.size() - 1; i < j; i++, j--)                swap(word[i], word[j]);            res += (res.size() ? " " : "") + word;        }        return res;    }};

这里写图片描述

原创粉丝点击