拼接最小字典序练习题


layout: post
title: “拼接最小字典序练习题”
date: 2015-5-15 16:14:09 +0800
categories: arithmetic

对于一个给定的字符串数组,请找到一种拼接顺序,使所有小字符串拼接成的大字符串是所有可能的拼接中字典序最小的。

给定一个字符串数组strs,同时给定它的大小,请返回拼接成的串。



     public class Mycomparator implements Comparator<String> {
 
        @Override
        public int compare(String a, String b) {
            // TODO Auto-generated method stub
            return (a + b).compareTo(b+a);
        }
 
    }
    public String findSmallest(String[] strs, int n) {
        // write code here
        if(strs == null || n==0){
            return "";
        }
        Arrays.sort(strs, new Mycomparator());
 
        String res = "";
        for (int i = 0; i < n; i++) {
            res += strs[i];
        }
        return res;
    }