首页 > 学院 > 开发设计 > 正文

Leetcode 151. Reverse Words in a String

2019-11-11 05:10:50
字体:
来源:转载
供稿:网友

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.

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.

s思路: 1. 这道题见过多次了。先全部reverse,然后对每个单词reverse。 2. 重点反而不是reverse,可以把reverse写成一个函数;重点是找到每个单词的开始结尾。可能有任意多个空格,导致不规则的情况,不规则的情况,我们一般用while来handle。

3.这道题还是比较复杂的,要求去掉所有冗余空格。现在这个方法比自己想到的方法简单得多,而且好实现!自己原先想的方法是:对空格计数,数完然后一起删;而别人家的代码,看空格的坐标,如果i=0或i=n-1,以及看这个坐标左右位置是否有单词决定是否删除这个空格,即:一个一个的判断,一个一个的删除。就不用计数了,简单! 4.这里面的逻辑是这样的:如果对空格计数,尤其是在头部和尾部的空格,不能用坐标判断,那对句中的空格和句首尾的空格就要分开处理,增加复杂性。这种情况下,就可以尝试不计数,而改用发现一个删除一个。以后做题的时候,定制化,比如统计空格的个数,虽然道理上没错,但是代码很繁复,还不如不去管这些信息,直接判断一个空格是否合法反而简单!也就是说,好的方法是实现起来容易,道理讲得明白即可,没有非那一种不可。思考的时候,不可以潜意识觉得那一种就绝对好或绝对差,更不能给某一种方法打标签,这样只会让自己执着一种方法,反而不利于独立自由之思考!

class Solution {public: void reverse(string&s,int begin,int end){ while(begin<end){ swap(s[begin],s[end]); begin++; end--; } } void reverseWords(string &s) { // int n=s.size(); reverse(s,0,n-1); int i=0,l=0,r=0; while(i<n){ if(s[i]==' '){ if(i>0&&i<n-1&&s[i-1]!=' '&&s[i+1]!=' '){ i++; l=i; r=i; }else{ s.erase(i,1);n--;//长度减一 } }else{ while(r<n&&s[r]!=' ') r++; reverse(s,l,r-1); i=r; } } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表