leetCode(34):Reverse Words in a String

原创 2015年07月08日 09:23:09

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.


        字符串反转的问题,有很多种方法。但本题要求删除多余的空格,所以比较特别,最直接的方法就是把所有单词取出来放到栈当中,再弹出。但题目要求不能用多余的辅助空间,所以只能在翻的时候去掉多余的空格。

class Solution {
public:
    void reverseWords(string &s) {
        reverse(s.begin(),s.end());
//首先去除头尾的空格
    	while(*(s.begin())==' ')
    	{
    		s.erase(s.begin());
    	}
    	
    	while(*(s.end()-1)==' ')
    	{
    		s.erase(s.end()-1);
    	}
    	string::iterator iter1=s.begin();
    	string::iterator iter2=s.begin();
    	
    	for(;iter2!=s.end();++iter2)
    	{
    		if(*iter2==' ' && *iter1!=' ')
    		{//反转每一个单词
    			reverse(iter1,iter2);
    			iter1=iter2+1;
    		}
    		else if(*iter2==' ' && *iter1==' ')
    		{//去除中间的空格
    			iter1--;
    			s.erase(iter2);
    			iter2=iter1;
    			iter1++;			
    		}
    	}
    	reverse(iter1,s.end());//最后一个单词
    }
};


Reverse words in a string-leetcode

  • 2014年08月30日 18:27
  • 197B
  • 下载

将一个英文句子单词顺序逆置(LeetCode | Reverse Words in a String)

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky...

【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】

【152-Reverse Words in a String(反转字符串中的单词)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given an input strin...

[LeetCode186]Reverse Words in a String II

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

[leetcode]151. Reverse Words in a String

Given an input string, reverse the string word by word.For example, Given s = "the sky is blue", ret...

LeetCode(151) Reverse Words in a String

题目Given an input string, reverse the string word by word.For example, Given s = “the sky is blue”, ...
  • fly_yr
  • fly_yr
  • 2015年11月01日 15:07
  • 634

《leetCode》:Reverse Words in a String

题目Given an input string, reverse the string word by word.For example, Given s = "the sky is blue", r...

LeetCode之186_Reverse Words in a String 字符串词序反转算法

给定一个字符串S,反转其中存在的单词顺序,将

[leetcode]151. Reverse Words in a String@Java解题报告

https://leetcode.com/problems/reverse-words-in-a-string/tabs/description Given an input s...

LeetCode OJ 之 Reverse Words in a String (翻转字符串的单词)

题目: Given an input string, reverse the string word by word.(给定一个输入字符串,按单词翻转这个字符串) For exampl...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetCode(34):Reverse Words in a String
举报原因:
原因补充:

(最多只允许输入30个字)