Smallest chosen word

You are given three strings 

s1s2, and s3. Let x be any subsequence of s2 (x can be an empty string). The name is in the form of (s1+x+s3), here (+) means concatenation of strings. You are required to print the lexicographically smallest string s.

Note: The string contains only lowercase letters.

Example:

Input: len1 = 3, len = 3, len2 = 3, s1 = "abc", s2 = "def", s3 = "ghi"
Output: abcdefghi

Approach

C++

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

bool comp(pair<charint&apair<charint&b)
{
    if (a.first == b.first)
        return a.second < b.second;
    return a.first < b.first;
}

string smallestChosenWord(int len1int lenint len2,
                          string s1string s2string s3)
{
    string x;
    int fl = 0;
    for (int i = 0i < len2i++)
    {
        if (s3[i] != s3[0])
        {
            if (s3[i] > s3[0])
                fl = 1;
            break;
        }
    }
    vector<pair<charint>> vp;
    for (int i = 0i < leni++)
        vp.push_back(make_pair(s2[i]i));
    sort(vp.begin(), vp.end(), comp);
    char c = s3[0];
    int ind = -1;
    for (int i = 0i < leni++)
    {
        if (ind > vp[i].second)
            continue;
        if (vp[i].first == c && !fl)
            break;
        if (vp[i].first > c)
            break;
        x.push_back(vp[i].first);
        ind = vp[i].second;
    }
    return s1 + x + s3;
}
int main()
{

    int len1 = 3len = 3len2 = 3;
    string s1 = "abc"s2 = "def"s3 = "ghi";

    cout << smallestChosenWord(len1lenlen2s1s2s3);

    return 0;
}


No comments:

Post a Comment