Concatenate all strings to produce the smallest lexicographic string
Title description
Given a string array strs, please find a splicing order so that the string composed of all the strings is the smallest lexicographical order among all possibilities, and return this string.
Enter a description:
The input contains multiple lines, the first line contains an integer n (1 ≤ n ≤ 1 0 5) n(1 \leq n \leq 10^5)n(1≤n≤105 ), represents the length of the string array strs, the next n lines, each line has a string, representing strs[i] (ensure that the length of all strings is less than 10).
Output description:
Output one line, containing a string, representing the string with the smallest lexicographic order returned.
Example 1
enter
2
abc
de
Output
abcde
Example 2
enter
2
b
ba
Output
bab
answer:
Greedy, define a comparator and concatenate it after sorting:
If str1+str2 <= str2+str1, then str1 is placed at the front, otherwise placed at the back. The proof of the specific greedy strategy can be seen in this part of the book.
Code:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
inline bool cmp( const string &s1, const string &s2 ) {
return s1+s2 < s2+s1;
}
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
string s;
vector<string> v;
while (n--) {
cin >> s;
v.push_back(s);
}
sort(v.begin(), v.end(), cmp);
for (auto it : v)
cout << it;
cout << endl;
return 0;
}