Leetcode | Reverse Words in a String | 抛砖引玉

Reverse Words in a String

  Total Accepted: 10990  Total Submissions: 79751

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.

第一次在leetcode上做题,时间复杂度和空间复杂度就没怎么考虑。简单介绍下思路:
1  从前往后遍历,过滤空格,读取单词
2  把读到的单词放到栈中
3  将栈中元素拷贝到string,单词间添加空格
Tips:考察边界情况,特别是空字符串("")和空格字符串(”   “)以及一个字符的情况(”a“)。另外,首尾的空格也要过滤。

源码:
    void reverseWords(string &s) {
    	stack<string> sta;
    	int i,j,k;
    	int size;
    
    	size = s.size();
    	if(size == 0)	        	//空字符串处理
    		return;
    
    	i=0;
    	j=size-1;
    	while(i <= j && s[i] == ' ')
    		i++;
    	while(j >= i && s[j] == ' ')
    		j--;
    	
    	while(i<=j)                 //考虑单个字符的情况
    	{
    		k = i;
    		while(i <= j && s[i] != ' ')
    			i++;
    		sta.push(s.substr(k, i-k));	
    		if(i >= j)	
    			break;
    		while(i <= j && s[i] == ' ')
    			i++;
    	}
    
    	string tmp="";
    	while(!sta.empty())        //空格字符串不进入此循环
    	{
    		if(!tmp.empty())
    			tmp.push_back(' ');
    		tmp.append(sta.top());
    		sta.pop();
    	}
    	s = tmp;
    }

写完之后网上查了一下,发现有很多写得比楼主牛逼多了,不得不感慨下自己的码渣水平。
算是多提供一种思路:http://www.tuicool.com/articles/uQ3E7b

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值