zoukankan      html  css  js  c++  java
  • leetCode(34):Reverse Words in a String 分类: leetCode 2015-07-08 09:23 124人阅读 评论(0) 收藏

    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());//最后一个单词
        }
    };


  • 相关阅读:
    java xpath
    structs2 Interceptor
    jetbrains idea web help
    Java xpath example code THE RIGHT WAY
    java xpath engine
    本地安装jruby到maven仓库,由于公司网络不给力
    skybe的linux下的版本下载
    mybastis学 rails有migration了
    Using Java from Ruby with JRuby IRB
    PropertyPlaceholderConfigurer
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687068.html
Copyright © 2011-2022 走看看