ITPub博客

首页 > > > [LeetCode] Reverse Words in a String

[LeetCode] Reverse Words in a String

作者:Ruiyuan Li 时间:2015-04-14 00:00:00 0 删除 编辑

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".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

解题思路:

1、若用C#实现,非常简单,用字符串的split函数,将非空的子串倒着连接起来即可。

2、C++似乎没有split函数,需要我们自己实现一下,返回vector类型。但是这样需要扫描两次字符串。

3、可以只扫描一次字符串。下面是代码。有几个特殊情况需要考虑(1)可能会有多个空格符(2)可能没有空格符

class Solution {
public:
    void reverseWords(string &s) {
        string result="";
        int len = s.length();
        string word="";
        for(int i=0; i


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825