String Sort [codingblocks]

Nishant is a very naughty boy in Launchpad Batch. One day he was playing with strings, and randomly shuffled them all. Your task is to help Nishant Sort all the strings ( lexicographically ) but if a string is present completely as a prefix in another string, then string with longer length should come first. Eg bat, batman are 2 strings and the string bat is present as a prefix in Batman - then sorted order should have - Batman, bat.

Input Format

N(integer) followed by N strings.

Constraints

N<=1000

Output Format

N lines each containing one string.

Sample Input

3

bat

apple

batman

Sample Output

apple

batman

bat

Explanation

In mathematics, the lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way words are alphabetically ordered based on the alphabetical order of their component letters.


Java Code:



/*
Amit Kumar
03-12-2020
IDE code: https://ide.geeksforgeeks.org/bfCU88Hs7h
*/

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

class Name {
    String name;

    Name(String name) {
        this.name = name;
    }
}

class SortByName implements Comparator<Name> {

    @Override
    public int compare(Name name1, Name name2) {
        if (name1.name.contains(name2.name) || name2.name.contains(name1.name)) {
            return name2.name.compareTo(name1.name);
        }
        return name1.name.compareTo(name2.name);
    }
}

public class Array_StringSort {
    public static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        int num = scan.nextInt();
        ArrayList<Name> names = new ArrayList<>();
        while (num-- >0) {
            String getname = scan.next();
            Name name = new Name(getname);
            names.add(name);
        }

        names.sort(new SortByName());
        for (Name nameObj: names){
            System.out.println(nameObj.name);
        }
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )