Hackerrank - Sentence Sorting aka String Sorting

 Sort the words of a sentence based on count of vowels in each words.

Rules.

1.Sort the words in ascending order of the vowels count.

2.If two words have same vowel count, the word which appeared first in sentence should be the first word in the output as well.

Input Format

String 'S' which includes of length <=10^5

Constraints

String length <= 10^5

Output Format

Word wise sorted string 'R'

Sample Input 0

Hello World Hi Welcome to Programming

Sample Output 0

World Hi to Hello Welcome Programming

Explanation 0

No. of vowels in each Word

Hello - 2

World - 1

Hi - 1

Welcome - 3

Programming - 3

Hence out put inorder of Vowels, incase words have same vowel count, the order in sentence is retained.

Hence the output.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result2 {

static class Token
{
int vowelCount;
String word;

Token(int vowelCount,String word)
{
this.vowelCount = vowelCount;
this.word = word;
}
}

public static String Sentence_sort(String str) {
// Converting the strings to arrays
String[] arr = str.split(" ");


// Creating an array to store the vowel count
int[] vowelCount = new int[arr.length];
String vowels = "aeiouAEIOU";

// Updating the vowel count for each string
for (int i = 0; i < arr.length; i++) {
int count=0;
String tempString = arr[i];
for (int j = 0; j < tempString.length(); j++) {
if(vowels.contains(tempString.charAt(j)+"")){
count++;
}
}
vowelCount[i] = count;
}

ArrayList<Token> wordCountList = new ArrayList<Token>();

for (int i = 0; i < arr.length; i++) {
wordCountList.add(new Token(vowelCount[i], arr[i]));
}

Collections.sort(wordCountList, (x,y) -> x.vowelCount - y.vowelCount);
String[] resArray = new String[wordCountList.size()];

for (int i = 0; i < resArray.length; i++) {
resArray[i] = wordCountList.get(i).word;
}

String result = Arrays.toString(resArray);
result = result.substring(1, result.length()-1);
result = result.replace(", "," ");
return result;
}

}

class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();
String result = Result2.Sentence_sort(str);

System.out.println(result);
}
}


Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting

Hackerrank - Day of the Programmer

Hackerrank - UNIQUE ARMSTRONG NUMBER