文章目录
- 1. 题目信息
- 2. 解题
- 2.1 栈
- 2.2 STL reverse()
1. 题目信息
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:输入: "Let's take LeetCode contest"
输出: "s'teL 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) {stack<char> 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;}
};