Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Last active June 13, 2018 16:05
Show Gist options
  • Save y-fedorov/3b637b18415757602a146ae224b75336 to your computer and use it in GitHub Desktop.
Save y-fedorov/3b637b18415757602a146ae224b75336 to your computer and use it in GitHub Desktop.
151. Reverse Words in a String
/*
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
Copyright © 2018 LeetCode
*/
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <cctype>
std::string reverseWords(std::string &s) {
auto sourceSize = s.size();
std::string resultStr;
resultStr.reserve(sourceSize);
std::string str;
str.reserve(sourceSize / 2 );
auto concatStr = [](std::string &str1, std::string &str2)-> std::string {
if (str2.length() == 0)
return str1;
return str1 + " " + str2;
};
bool prevSymbol = false;
for (auto &c : s) {
bool isSpace = std::isspace(c) != 0;
if (isSpace && prevSymbol) {
resultStr = concatStr(str, resultStr);
str = "";
prevSymbol = false;
continue;
}
else if (isSpace)
{
continue;
}
prevSymbol = true;
str += c;
}
if (str.length() != 0) {
resultStr = concatStr(str, resultStr);
}
return resultStr;
}
void checkValue(std::string input, std::string expected)
{
auto result = reverseWords(input);
if (result != expected) {
throw new std::runtime_error("Failed on \"" + input + "\" Expected: " + expected);
}
}
int main()
{
// Defaults from task
checkValue("the sky is blue", "blue is sky the");
checkValue(" the sky is blue ", "blue is sky the");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment