Reverse Words in a String III – LeetCode 557
Problem
Description
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Answer
Original
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: string reverseWords(string s) { if(s.size() < 2) return s; bool blank = false; unsigned prev = 0; for(unsigned i = 1; i != s.size(); ++i){ if(s[i] == ' '){ if(!blank){ reverse(s.begin() + prev,s.begin() + i); blank = true; } } else { if(blank){ prev = i; blank = false; } } } if(!blank){ reverse(s.begin() + prev,s.end()); } return s; } };
|
思路
想着写。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$16$ ms,排名$5.3\%$
Better
思路
还没看到更好的解法。