You are given three strings
, , and . Let be any subsequence of ( can be an empty string). The name is in the form of (), here () means concatenation of strings. You are required to print the lexicographically smallest string .
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<char, int> &a, pair<char, int> &b){if (a.first == b.first)return a.second < b.second;return a.first < b.first;}string smallestChosenWord(int len1, int len, int len2,string s1, string s2, string s3){string x;int fl = 0;for (int i = 0; i < len2; i++){if (s3[i] != s3[0]){if (s3[i] > s3[0])fl = 1;break;}}vector<pair<char, int>> vp;for (int i = 0; i < len; i++)vp.push_back(make_pair(s2[i], i));sort(vp.begin(), vp.end(), comp);char c = s3[0];int ind = -1;for (int i = 0; i < len; i++){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 = 3, len = 3, len2 = 3;string s1 = "abc", s2 = "def", s3 = "ghi";cout << smallestChosenWord(len1, len, len2, s1, s2, s3);return 0;}
No comments:
Post a Comment