题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
vector<string>Vecstr;
string tostr;
int len=numbers.size();
if(len<=0)
return tostr;
for(int i=0;i<len;i++)//转换成字符串,并存储在字符串数组里
{
tostr=to_string(numbers[i]);
Vecstr.push_back(tostr);
tostr.clear();
}
for(int i=0;i<len;i++)
for(int j= 0;j<len-1;j++)
if(Comp(Vecstr[j],Vecstr[j+1]))
Swap(Vecstr[j],Vecstr[j+1]);
for(int i=0;i<len;i++)
tostr+=Vecstr[i];
return tostr;
}
void Swap(string &s1,string &s2)//交换
{
string temp=s1;
s1.clear();
s1=s2;
s2.clear();
s2=temp;
}
bool Comp(string s1,string s2)
{
string s3=s1+s2;
string s4=s2+s1;
if(s3>s4)// 3 32> 32 3 s2应连接在前
return true;
return false;
}
};