且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

leetCode 151. Reverse Words in a String 字符串反转 | Medium

更新时间:2022-10-03 13:53:14

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

题目大意:

输入一个字符串,将单词序列反转。

思路1:

  1. 采用一个vector,来存放中间结果

  2. 将vector的结果倒序放入原字符串中。

思路2:

  1. 在字符串分割的时候,直接将单词倒序相加到临时串。

  2. 将临时串的结果放入原串中。

代码如下:(采用思路2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    void reverseWords(string &s) {
        string result = "";
        const int sLen = s.length();
        char *cs = new char[sLen + 1];
        strcpy(cs, s.data());
        char *p;
        p = strtok(cs, " ");
        while (p)
        {
            string tmp(p);
            result = tmp + " " + result;
            p = strtok(NULL, " ");
        }
        s.clear();
        s = result.substr(0,result.size() - 1);//将最开始加入的" "删除掉
    }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1840102