题目:有n个数字(n <= 50),输出由这n个数字组成的最大字符串。
解法:排序即可,坑点在于不能直接利用字符串之间的比较,例如90和9,如果采用字符串比较的话答案是909,而事实是990,所以在比较两个字符串时采用判断a + b 和 b + a的值。
代码:
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 50 + 10;
string s[maxn];
int n;
bool cmp(string a, string b) {
return a + b < b + a;
}
int main(){
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
while (scanf("%d", &n) == 1 && n) {
for (int i = 0; i < n; i ++) cin >> s[i];
sort(s, s + n, cmp);
for (int i = n - 1; i >= 0; i --) cout << s[i];
puts("");
}
return 0;
}