字符串连接(贪心)

输入n个字符串s[i],你要把他们按某个顺序连接起来,使得字典序最小。

(1 <= n <= 100) (每个字符串长度 <= 100) (字符串只包含小写字母)

Input

  1. 第一行一个整数n。

  2. 接下来每行一个字符串s[i]。

Output

一行一个字符串表示把输入的n个字符串按某个顺序连接之后的结果

Input示例

6
it
looks
like
an
easy
problem

Output示例

思路:用sort自定义cmp函数比较字符串字典序大小,排序后输出即可。

• 最容易想到的是按字典序排序。

• ⼀个反例是ba b,答案是bab⽽不是bba。

• 空字符最⼤还是最⼩?(字典中是最⼩)

• 如果认为是最⼤的话,反例是bc b,答案是bbc

• 对于任意2个字符串,如果交换后更优,就交换。

• 类似冒泡排序,相当于按照a + b < b + a排序。

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 120;

bool cmp(string a,string b){
	return a+b < b+a;
}

string s[MAXN];

int main(){
	int N;
	cin>>N;
	for(int i=0 ; i<N ; ++i){
		cin>>s[i];
	}	
	sort(s,s+N,cmp);
	for(int i=0 ; i<N ; ++i){
		cout<<s[i];
	}
	cout<<endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/vocaloid01/article/details/81179783
今日推荐