标签:字符串
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)
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);//将最开始加入的" "删除掉
}
};2016-08-18 20:32:00
本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1840102
leetCode 151. Reverse Words in a String 字符串反转 | Medium
标签:字符串
原文地址:http://qiaopeng688.blog.51cto.com/3572484/1840102