把数组排列成最小的数(Java)

把数组排列成最小的数

题目:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
代码:

/**
 * @desc 把数字翻译成字符串
 * @author zhaoliang
 * @date 20200413
 */
public class Main46 {
    public static void main(String[] args) {

        String ans = String.valueOf(12258);

        System.out.println(getTranslationCount(ans));
    }
    private static int getTranslationCount(String ans) {
        //字符串的长度
        int length = ans.length();
        //new一个长度一样的数组
        int [] counts =new int[length];

        int count;
        //从下往上避免重复子问题
        for (int i=length-1;i>=0;i--){

            if (i<length-1){
                count = counts[i+1];

            }else {
                count = 1;
            }
            if (i<length-1){
                //例如拿到5
                int digit1= ans.charAt(1)-'0';
                //例如拿到8
                int digit2 = ans.charAt(i+1) -'0';
                //例如58
                int converted =digit1*10+digit2;
                if(converted>=10 && converted<=25){
                    if (i<length-2){
                        count+=counts[i+2];
                    }else {
                        count+=1;
                    }
                }
            }
            counts[i] = count;
        }
        count = counts[0];
        return count;
    }

}

发布了71 篇原创文章 · 获赞 0 · 访问量 877

猜你喜欢

转载自blog.csdn.net/sinat_40968110/article/details/105488123