Leetcode Reverse Words in a String

来源:互联网 发布:青岛邮箱数据 编辑:程序博客网 时间:2024/06/06 03:37

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.
比较简单的一道题,先把整个字符串反转,然后对每一个单词进行反转,用i记录每个单词的开始位置,j记录每个单词的结束位置,同时i为负值来取出前、中、后多余的空格。定义两个变量i,j,不需要其他的变量
备注:对于reverse(),是左闭右开,即如果要反转“hi!”,那么是reverse(s.begin()+0,s.begin()+2+1).

class Solution {public:    void reverseWords(string &s) {        reverse(s.begin(),s.end());        for(int i=-1,j=0;j<s.length();j++){            if(s[j]==' '){                if(j==s.length()-1){s.erase(s.begin()+j);j-=2;i=-2;}//当最末尾为空格时,j需要减去2,因为外循环j+1                else if(i==-1){s.erase(s.begin()+j);j--;}                else{                    reverse(s.begin()+i,s.begin()+j);                    i=-1;                }            }else{                if(i==-1)i=j;                if(j==s.length()-1&&i>=0)reverse(s.begin()+i,s.begin()+j+1);//避免最后一个单词两次反转            }        }    }};
0 0
原创粉丝点击