leetcode 557. Reverse Words in a String III

来源:互联网 发布:易观智库 数据哪来的 编辑:程序博客网 时间:2024/06/05 21:59

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.

本题题意很简单,直接逆序处理即可

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>using namespace std;class Solution {public:    string reverseWords(string s)     {        int pre = 0;        for (int i = 0; i <= s.length(); i++)        {            if (i == s.length() || s[i] == ' ')            {                reverse(s.begin()+pre, s.begin()+i);                pre = i + 1;            }        }        return s;    }};
原创粉丝点击