此题不能直接将字符串排序直接拼接,而是要自己编写sort中的cmp函数,找到a+b与b+a的最小
JAVA程序:
package problems_2017_08_21;
import java.util.Arrays;
import java.util.Comparator;
public class Problem_04_LowestLexicography {
public static class MyComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
return (a + b).compareTo(b + a);
}
}
public static String lowestString(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
Arrays.sort(strs, new MyComparator());
String res = "";
for (int i = 0; i < strs.length; i++) {
res += strs[i];
}
return res;
}
public static void main(String[] args) {
String[] strs1 = { "jibw", "ji", "jp", "bw", "jibw" };
System.out.println(lowestString(strs1));
String[] strs2 = { "ba", "b" };
System.out.println(lowestString(strs2));
}
}
C++程序:
#include<iostream>
#include<string>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
bool Compare(string a,string b)
{
if((a+b).compare(b+a)>0)
return false;
else true;
}
string lowstring(string *a,int n)
{
if(a==NULL||n==0)
return 0;
sort(a,a+n,Compare);
string result="";
for(int i=0;i<n;i++)
result+=a[i];
return result;
}
int main()
{
string a[2]={"a","ab"};
cout<<lowstring(a,2)<<endl;
system("pause");
return 0;
}