Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, June 24, 2017

Sort Numbers Stored as String


Idea was to use comparator as lambda expression and check if length of two strings are same then return small one else return smallest string

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] unsorted = new String[n];
        for(int unsorted_i=0; unsorted_i < n; unsorted_i++){
            unsorted[unsorted_i] = in.next();
        }
        Arrays.sort(unsorted,(String a,String b)->
                    {
                         if(a.length()==b.length())
                        {
                            return a.compareTo(b);
                        }
                          return a.length() - b.length();  
                    });
        for(String str:unsorted)
        {
            System.out.println(str);
        }
        // your code goes here
    }
}

0 Comments:

Post a Comment

Stats