习题地址 https://www.acwing.com/problem/content/description/73/算法
题目描述
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。spa
为简单起见,标点符号和普通字母同样处理。指针
例如输入字符串”I am a student.”,则输出”student. a am I”。code
样例blog
输入:"I am a student." 输出:"student. a am I"
算法1
除开先翻转整个句子 再反转单词的作法 个人比较硬核 直接逐个双指针的翻转整个单词ip
代码字符串
class Solution { public: int findsubString(const string& s, string& revertStr ,size_t& findPos) { size_t start = s.find_last_not_of(' ', findPos); if (start == string::npos) { return -1; } findPos = start ; size_t end = s.find_last_of(' ', findPos); findPos = end; int len = 0; if (end == string::npos){ end = 0; len = start - end + 1; } else{ end++; len = start - end+1; } revertStr += s.substr(end, len); if (findPos == string::npos) return -1; revertStr += " "; return 1; } string reverseWords(string s) { if (s.empty()) return s; string res; size_t findPos = s.size()-1; int ret = findsubString(s, res, findPos); while (ret == 1) { ret = findsubString(s, res, findPos); } return res; } }; 做者:defddr 连接:https://www.acwing.com/solution/acwing/content/2907/ 来源:AcWing 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。