您的位置:首页 > 职场人生

剑指offer——面试题42-2:翻转单词顺序

2018-03-25 22:56 417 查看

剑指offer——面试题42-2:翻转单词顺序

Solution1:自己想的垃圾算法

对于c++中的string对象,substr()和erase()函数都是很常用的,常见用法必须熟练掌握!

class Solution {
public:
string ReverseSentence(string str) {
string str_copy = str, temp, result;
stack<string> res; //对字符串从前向后进行切割,用栈存储,实现逆序输出
while(str_copy.find(' ') != string::npos){
temp = str_copy.substr(0,str_copy.find_first_of(' '));
res.push(temp);
str_copy.erase(0, str_copy.find_first_of(' ') + 1);
}
res.push(str_copy);
while(res.size() > 1) {
result += res.top();
result += ' ';
res.pop();
}
result += res.top();
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: