LeetCode Reverse Words in a String III 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.
给定一个句子,要求把句子中的每个单词都逆序。 简单题,找空格,然后对每个单词reverse,直接调string::reverse或者自己写都可以。 代码如下: [cpp] class Solution { public: string reverseWords(string s) { int i = 0, j = 0, n = s.size(); while (j < n) { while (j < n&&s[j] != ‘ ‘)++j; reverse(s.begin() + i, s.begin() + j); i = ++j; } return s; } }; [/cpp] 本代码提交AC,用时23MS。]]>