Reverse Words in a String Solutions in C++
Number 151
Difficulty Medium
Acceptance 22.0%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/// Author : Hao Chen, Siwei Xu// Date : 2014-06-16#include <ctype.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>#include <string>#include <vector>#include <algorithm> // for std::reverseusing namespace std;void reverseWords(string &s) {bool wordStart = false;vector<string> v;const char *pHead =s.c_str();const char *pStr, *pBegin, *pEnd;for (pStr=pHead; *pStr!='\0'; pStr++) {if (!isspace(*pStr) && wordStart == false){wordStart = true;pBegin = pStr;continue;}if(isspace(*pStr) && wordStart==true){wordStart=false;pEnd = pStr;v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );}}if (wordStart==true){pEnd = pStr;v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );}if (v.size()>0){s.clear();char space=' ';vector<string>::iterator it;for (it=v.begin(); it!=v.end(); ++it) {s = s + *it;s.push_back(space);}s.erase(s.end()-1);}else{s.clear();}cout << "[" << s << "]" <<endl;}// inspired from <Programming Pearls> -- Handwavingvoid reverseWords2(string &s) {if (s.length() == 0) return;string result = "";if (s[s.length()-1] == ' ') {int last = s.find_last_not_of(' ') + 1;s.erase(last, s.length() - last);}int first = s.find_first_not_of(' ', 0);while (first != string::npos) {int wend = s.find(' ', first); // word endif (wend == string::npos) wend = s.length();string word = s.substr(first, wend - first);reverse(word.begin(), word.end());result += word;first = s.find_first_not_of(' ', wend); // next wordif (first == string::npos) break;result += ' ';}reverse(result.begin(), result.end());s.swap(result);}// C solution in O(1) spacevoid reverse(char *b, char *e) {for (--e; e - b > 0; b++, e--) {char t = *b;*b = *e;*e = t;}}void reverseWords(char *s) {char *p = s, *ws = NULL, *last = s;while (*p && *p == ' ') p++; // skip leading spacews = p;for ( ; *p; p++) {while (*p && *p != ' ') p++; // find word endreverse(ws, p);strncpy(last, ws, p-ws);last += (p-ws);while (*p && *p == ' ') p++; // for next wordws = p;if (*p == '\0') break;*last++ = ' ';}reverse(s, last);*last = '\0';}void test() {#define TEST(str) do { \char* s = strdup(str); \printf("\"%s\" => ", s); \reverseWords(s); \printf("\"%s\"\n\n", s); \free(s); \} while (0)TEST(" the blue sky is blue ");TEST(" ");}main(){string s;reverseWords(s);s=" ";reverseWords(s);s="1 ";reverseWords(s);s="love";reverseWords(s);s="i love cpp";reverseWords(s);test();}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description//// Author : liuyubobobo/// Time : 2018-08-10#include <iostream>#include <vector>using namespace std;/// Split and Reverse/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:void reverseWords(string &s) {vector<string> vec = split(s);if(vec.size() == 0){s = "";return;}reverse(vec.begin(), vec.end());s = vec[0];for(int i = 1; i < vec.size() ; i ++)s += " " + vec[i];}private:vector<string> split(const string& s){vector<string> res;int start = nextNonSpace(s, 0);for(int i = start + 1; i <= s.size() ;)if(i == s.size() || s[i] == ' ') {res.push_back(s.substr(start, i - start));start = nextNonSpace(s, i);i = start + 1;}elsei ++;return res;}int nextNonSpace(const string& s, int start){int i = start;for(; i < s.size() ; i ++)if(s[i] != ' ')return i;return i;}};int main() {string s1 = "the sky is blue";Solution().reverseWords(s1);cout << s1 << endl;string s2 = "";Solution().reverseWords(s2);cout << s2 << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description//// Author : liuyubobobo/// Time : 2018-08-12#include <iostream>#include <vector>using namespace std;/// Reverse then reverse:)/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:void reverseWords(string &s) {int start = nextNonSpace(s, 0);s = s.substr(start);start = 0;for(int i = start + 1; i <= s.size() ; )if(i == s.size() || s[i] == ' '){start = nextNonSpace(s, i);if(start != s.size())s = s.substr(0, i) + " " + s.substr(start);else{s = s.substr(0, i);break;}start = i + 1;i = start + 1;}elsei ++;reverse(s, 0, s.size() - 1);start = 0;for(int i = start + 1; i <= s.size() ; )if(i == s.size() || s[i] == ' '){reverse(s, start, i - 1);start = i + 1;i = start + 1;}elsei ++;}private:int nextNonSpace(const string& s, int start){int i = start;for(; i < s.size() ; i ++)if(s[i] != ' ')return i;return i;}void reverse(string& s, int start, int end){int i = start, j = end;while(i < j)swap(s[i++], s[j--]);}};int main() {string s1 = "the sky is blue";Solution().reverseWords(s1);cout << s1 << endl;string s2 = "";Solution().reverseWords(s2);cout << s2 << endl;string s3 = " 1 ";Solution().reverseWords(s3);cout << s3 << endl;string s4 = " a b ";Solution().reverseWords(s4);cout << s4 << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-words-in-a-string/description//// Author : liuyubobobo/// Time : 2018-08-12#include <iostream>#include <vector>using namespace std;/// Reverse then reverse/// really do all the things in place:)////// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:void reverseWords(string &s) {int search_start = nextNonSpace(s, 0);if(search_start == s.size()){s = "";return;}int start = 0;for(int i = search_start + 1; i <= s.size() ; )if(i == s.size() || s[i] == ' '){for(int j = search_start; j < i ; j ++)s[start++] = s[j];search_start = nextNonSpace(s, i);if(search_start == s.size()){s = s.substr(0, start);break;}elses[start++] = ' ';i = search_start + 1;}elsei ++;reverse(s, 0, s.size() - 1);start = 0;for(int i = start + 1; i <= s.size() ; )if(i == s.size() || s[i] == ' '){reverse(s, start, i - 1);start = i + 1;i = start + 1;}elsei ++;}private:int nextNonSpace(const string& s, int start){int i = start;for(; i < s.size() ; i ++)if(s[i] != ' ')return i;return i;}void reverse(string& s, int start, int end){int i = start, j = end;while(i < j)swap(s[i++], s[j--]);}};int main() {string s1 = "the sky is blue";Solution().reverseWords(s1);cout << s1 << endl;string s2 = "";Solution().reverseWords(s2);cout << s2 << endl;string s3 = " 1 ";Solution().reverseWords(s3);cout << s3 << endl;string s4 = " a b ";Solution().reverseWords(s4);cout << s4 << endl;return 0;}