剑指offer:翻转单词顺序列

题目描述

JOBDU最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

class Solution {
public:
    string ReverseSentence(string str) {
        int len = 0;
		int start = 0, end = 0;
		int i = 0;
		
		/* 先从头到尾逆序 */
		convent(str,0,str.size() - 1);

		/* 把空格再逆序 */
		len = str.size();
		for(i = 0; i < len; i++)
		{
			/* 跳过空格,可能开头,或者单词中间有很多空格 */
			while(str[i] == ' ')
			{
				start++;
				end++;
				i++;
			}

			/* 判断下一个是否是空格,或者是结束 */
			if(str[i+1] == ' ' || (i+1) == len)
			{
				end = i;
				convent(str,start,end);
				
				start = i+1;
				end = i+1;
			}
		}

		return str;

    }

	void convent(string& str,int start,int end)
	{
		char ch = 0;

		while(start < end)
		{
			ch = str[start];
			str[start] = str[end];
			str[end] = ch;

			start++;
			end-- ;
		}
	}
};

int main()
{
	
	Solution s;
	string str;
	str = "Ii am a student.";

	cout << s.ReverseSentence(str) << endl; 

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmfrm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值