[LeetCode] Reverse Words in a String II

本文介绍了一种使用C++实现字符串中单词翻转的方法,通过整体反转字符串,然后逐个反转单词来解决空间复杂度问题。代码示例清晰展示了实现过程。

Problem Description:

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Since this problem has guaranteed that the string does not contain all the leading and trailing spaces and all words are separated by a single space, it will be much easier to be solved in space. The idea is to reverse the whole string first. Then we visit the string from left to right, each time we meet a space, we reverse the immediate word before it.

The code is as follows.

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         reverse(s.begin(), s.end());
 5         s += ' ';
 6         int i = 0, j = 0, n = s.length();
 7         while (i < n && j < n) {
 8             while (j < n && s[j] != ' ') j++;
 9             if (j < n) {
10                 reverseBetween(s, i, j - 1);
11                 i = j + 1;
12                 j = i;
13             }
14         }
15         s.resize(n - 1);
16     }
17 private:
18     void reverseBetween(string &s, int i, int j) {
19         while (i < j)
20             swap(s[i++], s[j--]);
21     }
22 };

Note that we append a space to the reversed string to facilitate the detection of the last word.

转载于:https://www.cnblogs.com/jcliBlogger/p/4600353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值