企业做网站公司哪家好,学校网站建设通知,wordpress 关闭头像,免费推广平台大全文章目录1. 题目信息2. 解题2.1 栈2.2 STL reverse()1. 题目信息
给定一个字符串#xff0c;你需要反转字符串中每个单词的字符顺序#xff0c;同时仍保留空格和单词的初始顺序。
示例 1:输入: Lets take LeetCode contest
输出: steL ekat edoCteeL tse…
文章目录1. 题目信息2. 解题2.1 栈2.2 STL reverse()1. 题目信息
给定一个字符串你需要反转字符串中每个单词的字符顺序同时仍保留空格和单词的初始顺序。
示例 1:输入: Lets take LeetCode contest
输出: steL ekat edoCteeL tsetnoc 注意在字符串中每个单词由单个空格分隔并且字符串中不会有任何额外的空格。
来源力扣LeetCode 链接https://leetcode-cn.com/problems/reverse-words-in-a-string-iii 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。
2. 解题
2.1 栈
利用栈反序输出
class Solution {
public:string reverseWords(string s) {stackchar stk;string ans;for(int i 0; i s.size(); i){if(s[i] ! i ! s.size()-1){stk.push(s[i]);}else if(s[i] ! i s.size()-1){ans.push_back(s[i]);while(!stk.empty()){ans.push_back(stk.top());stk.pop();}}else{while(!stk.empty()){ans.push_back(stk.top());stk.pop();}ans.push_back(s[i]);}}return ans;}
};2.2 STL reverse() class Solution {
public:string reverseWords(string s) {string ans, substr;for(int i 0; i s.size(); i){if(s[i] ! i ! s.size()-1){substr.push_back(s[i]);}else if(s[i] ! i s.size()-1){substr.push_back(s[i]);reverse(substr.begin(),substr.end());ans substr;}else{reverse(substr.begin(),substr.end());ans substr;substr ;ans.push_back(s[i]);}}return ans;}
};