拼接所有的字符串产生字典序最小的字符串

拼接所有的字符串产生字典序最小的字符串

题目描述

给定一个字符串的数组strs,请找到一种拼接顺序,使得所有的字符串拼接起来组成的字符串是所有可能性中字典序最小的,并返回这个字符串。

输入描述:

输入包含多行,第一行包含一个整数 n ( 1 ≤ n ≤ 1 0 5 ) n(1 \leq n \leq 10^5) n(1n105),代表字符串数组strs的长度,后面n行,每行一个字符串,代表strs[i](保证所有字符串长度都小于10)。

输出描述:

输出一行,包含一个字符串,代表返回的字典序最小的字符串。

示例1
输入
2
abc
de
输出
abcde
示例2
输入
2
b
ba
输出
bab

题解:

贪心,定义一个比较器,排序之后在拼接起来:

若 str1+str2 <= str2+str1,则 str1 放在前面,否则放在后面。具体贪心策略证明,可见书上该部分。

代码:
#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;
}

猜你喜欢

转载自blog.csdn.net/MIC10086/article/details/108942803
今日推荐