# Leetcode 557. Reverse Words in a String III ###### tags: `Leetcode(C++)` 題目 : https://leetcode.com/problems/reverse-words-in-a-string-iii/ 。 想法 : 遇到空格或是截尾就翻轉那個單字。 時間複雜度 : O(n)。 程式碼 : ``` class Solution { public: string reverseWords(string s) { int l=s.size(), first=0, last=0; for(int i=0 ; i<=l ; i++){ if(s[i] == ' ' || i == l){ last=i-1; cout << first << " " << last << endl; for(int j=0 ; j<=(last-first)/2 ; j++){ char tmp = s[first+j]; s[first+j] = s[last-j]; s[last-j] = tmp; } first=i+1; } } return s; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up