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.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
C++(22ms):
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 int left = 0 ; 5 for (int i = 0; i <= s.length(); i++) { 6 if ( i == s.length() || s[i] == ' ') { 7 reverse(s.begin() + left , s.begin() + i) ; 8 left = i+1 ; 9 } 10 } 11 12 return s; 13 } 14 };
C++(43ms):
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 int left = 0 ; 5 int num = 0 ; 6 string ans = "" ; 7 for(int i = 0 ; i < s.size() ; i++){ 8 if (s[i] != ' '){ 9 num++ ; 10 } 11 else if (s[i] == ' '){ 12 string t = s.substr(left,num) ; 13 reverse(t.begin(),t.end()); 14 ans += t + ' ' ; 15 left = i+1 ; 16 num = 0 ; 17 } 18 19 } 20 string t = s.substr(left,s.size()) ; 21 reverse(t.begin(),t.end()); 22 ans += t ; 23 return ans ; 24 } 25 };
C++(29ms):
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 for (int i = 0; i < s.length(); i++) { 5 if (s[i] != ' ') { 6 int j = i; 7 while(j < s.length() && s[j] != ' ') 8 j++; 9 reverse(s.begin() + i, s.begin() + j); 10 i = j; 11 } 12 } 13 14 return s; 15 } 16 };