题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
解法1: 栈
class Solution { public: string ReverseSentence(string str) { int len = str.length(); if (len == 0) return ""; stack<string> s; // 注意压栈的是单词 for (int i = 0; i < len; ++i) { int j = i; while (j < len && str[j] != ' ') j++; // 跳过空格 // cout << "i == " << i << ", j == " << j << endl; s.push(str.substr(i, j - i)); i = j; // 跳过空格 } string result = ""; while (!s.empty()) { result += s.top(); s.pop(); if (!s.empty()) { result += " "; } } return result; } }; // 0123456789 // nowcoder. a am I
解法2: 双指针
// 0123456789abcdef // nowcoder. a am I // class Solution { public: string ReverseSentence(string str) { int len = str.length(); if (len == 0) return ""; int i = len - 1; int j = i; string result = ""; while (i >= 0) { if (i != len - 1) { // 处理空格 result += " "; } while (i >= 0 && str[i] != ' ') i--; cout << "i == " << i << ", j == " << j << endl; result += str.substr(i+1, j - i); while (i >= 0 && str[i] == ' ') i--; j = i; } return result; } };
2023-剑指-队列 + 栈 文章被收录于专栏
2023-剑指-队列 + 栈