top of page

Daily Coding Problem #6

Writer's picture: Mischievous_FaceMischievous_Face

// 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;

}

365 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page