// Source : https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
// Date : 2021-11-24
class Solution { public: string reverseWords(string s) { int length = s.length(), i = 0; while (i < length) { int start = i; while (i < length && s[i] != ' ') i++; //处理每个单词 int left = start, right = i - 1; while (left < right) { swap(s[left], s[right]); left++; right--; } //此时i停留在空格,因此需要将i后移 // while (i < length && s[i] == ' ') i++; } return s; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)