您的位置:首页 > 其它

将一个字符串数组中的字符串拼接出来,使得字典序最小

2017-08-22 17:03 330 查看
此题不能直接将字符串排序直接拼接,而是要自己编写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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐