本文共 826 字,大约阅读时间需要 2 分钟。
给定一个字符串,逐个翻转字符串中的每个单词。
样例
给出s = “the sky is blue”,返回"blue is sky the"说明
单词的构成:无空格字母构成一个单词 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个#include#include #include #include #include using namespace std;string reverseWords(string &s) { int i = s.size()-1; string res; while (i >= 0) { while (i >= 0 && s[i] == ' ') { i--; } if (i < 0) break; if (res.size() != 0) { res.append(" "); } string temp; while (i >= 0 && s[i] != ' ') { temp.push_back(s[i]); i--; } reverse(temp.begin(), temp.end()); res.append(temp); } return res;}int main() { string s; getline(cin, s); cout << reverseWords(s) << endl; return 0;}
转载地址:http://nicpn.baihongyu.com/