leetcode.557.Reverse Words in a String III

来源:互联网 发布:java 接口 编辑:程序博客网 时间:2024/05/21 10:03

Description

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.

sln

c++的标准库中有提供一个reverse函数,能够对字符串做反转。我们的题目要求我们将每个单词进行反转,但不对句子进行反转,所以我们只要把这个问题分解成多个单词反转的问题即可。顺序遍历字符串,每次遇到空格就把该上一个空格开始到这一个空格前的子串进行反转即可。c++实现如下:

class Solution {public:    string reverseWords(string s) {        int last_space = 0;        for (int i = 0; i <= s.length(); ++i) {            if (i == s.length() || s[i] == ' ') {                reverse(&s[last_space], &s[i]);                last_space = i + 1;            }        }        return s;    }};