面试经典150题 P151 反转字符串中的单词 Created:2025-11-09 21:16:13Updated:2025-11-09 21:16:13algorithmalgorithm, leetcode面试经典150题, 字符串字数 254阅读 访客 时间轴 时间轴2025-11-09init stringstream 题目:P151 反转字符串中的单词https://leetcode.cn/problems/reverse-words-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150stringstream用 stringstream 获得每个单词:123456789101112131415161718192021222324252627282930#include <sstream>#include <stack>#include <string>using std::stringstream;using std::string;using std::stack;class Solution { public: string reverseWords(string s) { stack<string> st; stringstream ss(s); string tmp, res; while (ss >> tmp) { st.push(tmp); } while (!st.empty()) { tmp = st.top(); st.pop(); res += tmp; res += " "; } res.pop_back(); // 去掉最后一个空格 return res; }};双指针也可以用双指针123456789101112131415161718class Solution {public: string reverseWords(string s) { // 使用双指针 int m = s.size() - 1; string res; // 除去尾部空格 while (s[m] == ' ' && m > 0) m--; int n = m; // n是另一个指针 while (m >= 0) { while (m >= 0 && s[m] != ' ') m--; res += s.substr(m + 1, n - m) + " "; // 获取单词并加上空格 while (m >= 0 && s[m] == ' ') m--; n = m; } return res.substr(0, res.size() - 1); // 忽略最后一位的空格 }};