557. Reverse Words in a String III 發表於 2023-02-13 | 分類於 leetcode problemsolution123456789101112131415161718192021class Solution {public: void reverse(string &s, int l, int r){ while(l<r) swap(s[l++], s[r--]); } string reverseWords(string s) { int pre = 0; for(int i=0;i<s.size() ;++i){ char c =s[i]; if(c==' '){ // reverse(s.begin()+pre, s.begin()+i); reverse(s, pre, i-1); pre = i+1; } } // reverse(s.begin()+pre, s.end()); reverse(s, pre, s.size()-1); return s; }}; analysis time complexity O(n) space complexity O(1)