// Given a string and a set of delimiters, reverse the words in the string while maintaining the relative
// order of the delimiters.For example, given "hello/world:here", return "here/world:hello"
// Follow - up: Does your solution work for the following cases : "hello/world:here/", "hello//world:here"
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <queue>
using namespace std;
string delimiterReverse(const string str, vector<char> delimiters)
{
string result = "";
queue<char> delimitersFound;
stack<string> words = stack<string>();
unsigned lastIndex = 0;
for (unsigned i = 0; i < str.length(); ++i)
{
for (unsigned j = 0; j < delimiters.size(); ++j)
{
if (str[i] == delimiters[j])
{
// we encountered a delimiter
delimitersFound.push(str[i]);
words.push(str.substr(lastIndex, i - lastIndex));
lastIndex = i + 1;
break;
}
}
// edge case to check for a word with no final delimiter
if (i == (str.length()-1) && (str[i] != delimitersFound.front()))
{
words.push(str.substr(lastIndex, i - lastIndex + 1));
}
}
while(!words.empty())
{
if (!words.empty())
{
result += words.top();
words.pop();
}
if (!delimitersFound.empty())
{
result += delimitersFound.front();
delimitersFound.pop();
}
}
return result;
}
int main(int argc, char** argv)
{
vector<char> delimiters = {':', '/'};
auto result = delimiterReverse("hello/world:here/", delimiters);
cout << result << endl;
return 0;
}
Comments