翻转字符串中的单词

本题目来自LeetCode,具体如下:

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

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

click to show clarification.

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.
我的思路:
1.可以使用先翻转每一个单词,然后再对整个字符串进行整体翻转。
          这种方法针对本题目有个缺点,由于要求“ your reversed string should not contain leading or trailing spaces.”并且 “ Reduce them to a single space in the reversed string.”, 因此在对字符串完成整体翻转之后还需要额外的处理,去掉前后的空格,将单词间多个空格换成一个。
2.借住辅助栈,从前向后将单词逐个入栈,然后再逐个出栈,放入结果字符串中,同时两个字符串之间用空格隔开。
这两种算法的时间复杂度都是O(n),是第二种方法的空间复杂度较高,但是从时间复杂度上来说,第二种方法的常数项要小,因此第二种方法的时间复杂度更好些。同时第二种方法处理简单,不需要对字符串中的空格进行繁琐的处理。

下面贴出AC过的代码,如有问题,欢迎大家批评指正:
class Solution {
public:
	void reverse(string&s, int start, int end) 
	{
		if (start >= end - 1) return ;
		std :: reverse(s.begin() + start, s.begin() + end ) ;
	} ;
	void reverseWords(string &s) {
		stack<string> words ;
		int start = 0 ;
		int end = 0 ;
		while (true)
		{
			start = s.find_first_not_of(' ', end) ;
			if (start == string :: npos) break ;
			end = s.find_first_of(' ', start) ;
			if (end == string :: npos)
				end = s.length() ;
			words.push(s.substr(start, end - start)) ;
			if (end == s.length())
				break ;
		}
		s.clear() ;
		if (!words.empty())
		{
			while (words.size() > 1)
			{
				s.append(words.top()) ;
				words.pop() ;
				s.append(" ") ;
			}
			s.append(words.top()) ;
			words.pop() ;
		}
	};

};



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值