151. Reverse Words in a String

Given an input string, reverse the string word by word.

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

题目要求将一串单词倒置,即单词保持不变,单词的顺序倒过来。如果忽略空间复杂度为O(1),可以直接用栈来做;如果要实现空间复杂度为O(1),则要在原字符串上操作。想法是先把每个单词倒置,然后整个句子倒置。要注意的是空格的问题。字符串的前面可能有空格,单词和单词之间的空格也不一定只有一个,所以要把空格全弄到字符串的后面(单词和单词之间留一个)。则把单词和单词前面的空格一起倒置,如"  abc"变成“cba  " ,然后留一个空格,其后的单词也这样操作。如”  abc   dce“变成”cba ecd    "。最后用resize函数重新定字符串的长和用reverse函数将整个字符串倒置。

代码:
class Solution {
public:
void reverse(string &s,int l,int r)
{
	while(l<r) swap(s[l++],s[r--]);
}
void reverseWords(string &s)
{
	if(s.empty()) return;
	s+="  ";
	int n=s.size();
	int l=0,r=0,flg=0;
	while(l<n)
	{
		int wl=0;
		while(s[r]==' '&&r<n) r++;
		while(s[r]!=' '&&r<n) { wl++; r++; }
		if(wl==0) break;
		reverse(s,l,r-1);
		l=l+wl+1;
		r=l;
		flg=1;
	}
	if(flg==0) 
	{
		s.resize(0);
		return;
	}
	s.resize(l-1);
	reverse(s,0,l-2);
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值