题解 | #牛群消息传递#
牛群消息传递
https://www.nowcoder.com/practice/28df6c40150a40b49c9c4d4ae1dd675d
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ string reverseWords(string s) { string ans; // 定义一个存储临时string的变量 while (s.rfind(" ") != -1) // 当字符串s中还存在空格时 { if (s.find(" ") == 0) // 若字符串首字符为空格 { s.erase(0,1); // 删除首字符 } else if (s.rfind(" ") == s.size() - 1) // 若字符串末字符为空格 { s.erase(s.size() - 1, 1); // 删除末字符 } else { int pos = s.rfind(" "); // 从后往前找出空格所在位置 string tmp = s.substr(pos + 1, s.size() - 1 - pos); // 截取空格往后的子串 ans += tmp; // 放入临时string变量tmp中 ans += " "; // 两个子串中间用空格进行分割 s = s.erase(pos, tmp.size()+1); // 删除包括空格在内的子串 } } // 当字符串中没有空格时 ans += s; // 将剩余的最后一个子串进行拼接 return ans; } };