Cover image for 面试经典150题 P151 反转字符串中的单词

面试经典150题 P151 反转字符串中的单词


时间轴

时间轴

2025-11-09

init

stringstream

题目:

stringstream

用 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;	}};

双指针

也可以用双指针

123456789101112131415161718
class 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); // 忽略最后一位的空格    }};
评论加载中…