首页 > 代码库 > Leetcode 151. Reverse Words in a String 解题报告

Leetcode 151. Reverse Words in a String 解题报告

[Problem]

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.


[Idea]

从左往右遍历一次,每当遇到空格暂停,记录暂停位置作为开始点,移动二指针到下一个空格前的位置或者字符串末尾,则找到一个word。用一个新的空字符串result倒序存储每一个word。

双指针的方法。思想和实现都很简单。

[Code]

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         string result = "";
 5         for (int i = 0; i < s.length(); i++) {
 6             if (s[i] !=  ) {
 7                 int pos = i;
 8                 while (i < s.length() && s[i] !=  ) i++;
 9                 if (result.length() > 0) result =   + result;
10                 result = s.substr(pos, i - pos) + result;
11                 i--;            
12             }
13         }
14         s = result;
15     }
16 };

update:

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         string result;
 5         int i = 0;
 6         while(i < s.size()) {
 7             if(i < s.size() && s[i] ==  ) {i++; continue;}
 8             string word;
 9             while(i < s.size() && s[i] !=  ) {
10                 word += s[i];
11                 i++;
12             }
13             if(result != "") result =   + result;
14             result = word + result;
15         }
16         s = result;
17     }
18 };

[Reference]

喜刷刷

Leetcode 151. Reverse Words in a String 解题报告