[LeetCode]Reverse Words in a String

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.

 

Have you been asked this question in an interview? 

思考:一开始没有考虑空格。去掉不合法空格+两次翻转,不需要额外空间。

class Solution {
public:
    void reverseWords(string &s) {
        int len=s.length();
        int i=0,j=len-1;
        //去掉前后空格
        while(i<len&&s[i]==' ') i++;
        while(j>=0&&s[j]==' ') j--;	
        len=j-i+1;
        s=s.substr(i,len);
        //去掉中间空格
        for(i=0;i<s.length();i++)
        {
            if(s[i]==' ')
			{
				j=i+1;
				while(s[j]==' ') j++;
				s.erase(i+1,j-i-1);
			}
        }
        len=s.length();
        for(i=0;i<len/2;i++) swap(s[i],s[len-i-1]);
        int start=0;
        for(i=0;i<=len;i++)
        {
            if((i<len&&s[i]==' ')||i==len)
            {
                for(j=start;j<(i+start)/2;j++) swap(s[j],s[i-(j-start)-1]);
				start=i+1;
            }
        }
    }
};

  

posted @ 2014-03-09 20:56  七年之后  阅读(323)  评论(0编辑  收藏  举报