【华为机试】—— 14.字串的连接最长路径查找

时间:2021-01-21 14:44:02

题目

【华为机试】—— 14.字串的连接最长路径查找

 

解法

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        int num = Integer.valueOf(sc.nextLine());
        
        ArrayList<String> list = new ArrayList<>();
        
        for(int i=0;i<num;i++){
            list.add(sc.nextLine());
        }
        
        Collections.sort(list, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // TODO Auto-generated method stub
                char[] arr1 = o1.toCharArray();
                char[] arr2 = o2.toCharArray();
                
                int ptr1 = 0;
                int ptr2 = 0;
                
                for( ; ptr1 < arr1.length  && ptr2 < arr2.length; ptr1++,ptr2++ ){
                    if(arr1[ptr1] < arr2[ptr2]){
                        return -1;
                    }else if(arr1[ptr1] > arr2[ptr2]){
                        return 1;
                    }
                }
                
                if(ptr1 == arr1.length && ptr2 == arr2.length)
                    return 0;
                return ptr1 == arr1.length ? -1 : 1; 
             }
        });
        
        
        for(String string : list){
            System.out.println(string);
        }
    }
}