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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 解题报告的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode151. Reverse Words in a String

刷题-LeetCode151 Reverse Words in a String

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

leetcode 151. Reverse Words in a String --------- java

leetcode-151-reverse word in a string

leetcode-Reverse Words in a String-151