更新时间: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:
采用一个vector,来存放中间结果
将vector的结果倒序放入原字符串中。
思路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); //将最开始加入的" "删除掉
}
};
|