Reverse String while maintaining relative order of delimiters

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"

Example:

Input:  str = "hello/world:here", delimeters = {':', '/'}
Output: here/world:hello

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string delimiterReverse(string str,
                        vector<char&delimiters)
{
    string res = "";
    queue<chardelimitersFound;
    stack<stringwords = stack<string>();
    int lastIndex = 0;

    for (int i = 0i < str.length(); ++i)
    {
        for (int j = 0j < delimiters.size(); ++j)
        {
            if (str[i] == delimiters[j])
            {
                delimitersFound.push(str[i]);
                words.push(str.substr(lastIndexi - lastIndex));
                lastIndex = i + 1;
                break;
            }
        }
        if (i == (str.length() - 1) && (str[i] !=
                                        delimitersFound.front()))
        {
            words.push(str.substr(lastIndexi - lastIndex + 1));
        }
    }
    while (!words.empty())
    {
        if (!words.empty())
        {
            res += words.top();
            words.pop();
        }
        if (!delimitersFound.empty())
        {

            res += delimitersFound.front();
            delimitersFound.pop();
        }
    }
    return res;
}

int main()

{

    string str = "hello/world:here";

    vector<chardelimiters = {':''/'};
    cout << delimiterReverse(strdelimiters);

    return 0;
}


No comments:

Post a Comment