I need to print all the letters that appear in the word, rearranged so that the letters that appear most frequently are found at the beginning.
If there are letters that appear the same number of times, the smallest ones will be displayed first after alphabetical sorting.
I've tried something but I'm getting output limit exceed.
How can I use BufferedWriter to make this solution run faster? Should I use HashMap?
Input:intructions
Output:iinnssttcoru
public class Main {
public static void main(String[] args) throws IOException {
String inputString;
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
inputString = reader.readLine();
if(reader != null)
reader.close();
int[] letterArray = new int[26];
char[] letters = new char[26];
for(int i=0;i<=25;i++)
letters[i] = (char)(97+i);
for(int i=0; i< inputString.length(); i++)
letterArray[inputString.charAt(i) - 97] +=1 ;
for(int i=0; i<=24;i++)
for(int j=i+1;j<=25;j++){
if(letterArray[i] <letterArray[j] || (letterArray[i] ==
letterArray[j] && letters[i] > letters[j])){
int temp = letterArray[i];
letterArray[i] = letterArray[j];
letterArray[j] = temp;
char temp2;
temp2 = letters[i];
letters[i] = letters[j];
letters[j] = temp2;}
}
String outputString = new String();
for(int i=0;i<=25;i++){
for(int j = 0; j<letterArray[i]; j++)
outputString += letters[i];}
System.out.println(outputString);}
}
My second idea:
public class Main {
public static void main(String[] args) throws IOException {
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
line = reader.readLine();
StringBuilder sb = new StringBuilder();
Map<Character, Integer> charCountMap = new HashMap<>();
int len = line.length();
for (int i = 0; i < len; i++) {
char ch = line.charAt(i);
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}