您的位置:首页 > 编程语言 > C语言/C++

[C++]判断最大字符串

2016-04-11 22:15 399 查看

判断最大字符串

题目描述如下:

Giving N numbers, try to use them to construct a max number.

For example, there are three numbers 56 54 5, you can make numbers 56545, 56554, 54565, 54556, 55654, 55456. The answer is the max number 56554. It is guranteed that all numbers are positive integers and less than 1000.

There is only two lines in Input.

First line is a integer N which means that there are N positive integers.

Second lines are N positive integers.

Sample Inputs

3

56 54 5

Sample Output

56554

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;
bool compare_bewteen_strings(string a, string b) {
for (int j = 0; j != b.length(); j++) {
if (b[j] > a[j]) {
return false;
}
if (b[j] < a[j]) {
return true;
}
}
int i = 0;
while (b[b.length() - 1] == a[b.length() + i]) {
if (b.length() + i == a.length()) {
return true;
} else {
if (b[b.length() - 1] > a[b.length() + i]) {
return false;
} else if (b[b.length() - 1] < a[b.length() + i]) {
return true;
}
}
i++;
}
if (b[b.length() - 1] > a[b.length()]) {
return false;
} else {
return true;
}
}
bool special_cmp(string a, string b) {
if (a.length() > b.length()) {
return compare_bewteen_strings(a, b);
}
if (b.length() > a.length()) {
return (!compare_bewteen_strings(b, a));
}
if (a.length() == b.length()) {
for (int i = 0; i != a.length(); i++) {
if (a[i] > b[i]) {
return true;
}
if (a[i] < b[i]) {
return false;
}
}
}
return true;
}
int main() {
vector<string> test;
int n;
cin >> n;
string temp;
for (int i = 0; i != n; i++) {
cin >> temp;
test.push_back(temp);
}
sort(test.begin(), test.end(), special_cmp);
for (vector<string>::iterator iter = test.begin();
iter != test.end(); iter++) {
cout << *iter;
}
cout << endl;
return 0;
}


答案用的是相邻两个字符串相加,判断谁加谁更大。(相当精妙。)

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::sort;
using std::endl;
using std::string;
using std::vector;
bool cmp(string a, string b) {
return a+b > b+a;
}
int main() {
int N;
string tmp;
vector<string> max;
vector<string>::iterator iter;
cin >> N;
while (N--) {
cin >> tmp;
max.push_back(tmp);
}
sort(max.begin(), max.end(), cmp);
if (!max.empty()) {
for (iter = max.begin(); iter != max.end(); ++iter) {
cout << *iter;
}
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: