Given Alphabet ={c,b,a,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}, String array ={cab,cba,abc}, return{cba,cab,abc}.
Explanation:
According to the new dictionary order, output the sorted result {cba, cab, abc}.
Given Alphabet ={z,b,a,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,c}, String array ={bca,czb,za,zba,ade}, return{zba,za,bca,ade,czb}.
Explanation:
According to the new dictionary order, output the sorted result {zba,za,bca,ade,czb}.
publicclassSolution { /** * @param alphabet: the new alphabet * @param words: the original string array * @return: the string array after sorting */publicString[] wordSort(char[] alphabet,String[] words) {// Write your code hereArrays.sort(words,newWordComparator(alphabet));return words; }classWordComparatorimplementsComparator<String> {Map<Character,Integer> map =newHashMap<>();publicWordComparator(char[] alphabet) {for (int i =0; i <alphabet.length; i++) {map.put(alphabet[i], i); } }publicintcompare(String a,String b) {int minLen =Math.min(a.length(),b.length());for (int i =0; i < minLen; i++) {int aValue =map.get(a.charAt(i));int bValue =map.get(b.charAt(i));if (aValue == bValue) {continue; } else {return aValue - bValue; } }returna.length() -b.length(); } }}
Sort by Frequency:
importjava.util.*; publicclassGFG { // Driver Code publicstaticvoidmain(String[] args) { // Declare and Initialize an array int[] array = { 4,4,2,2,2,2,3,3,1,1,6,7,5 }; Map<Integer,Integer> map =newHashMap<>(); List<Integer> outputArray =newArrayList<>(); // Assign elements and their count in the list and map for (int current : array) { int count =map.getOrDefault(current,0); map.put(current, count +1); outputArray.add(current); } // Compare the map by value SortComparator comp =newSortComparator(map); // Sort the map using Collections CLass Collections.sort(outputArray, comp); // Final Output for (Integer i : outputArray) { System.out.print(i +" "); } } } // Implement Comparator Interface to sort the values classSortComparatorimplementsComparator<Integer> { privatefinalMap<Integer,Integer> freqMap; // Assign the specified map SortComparator(Map<Integer,Integer> tFreqMap) { this.freqMap= tFreqMap; } // Compare the values @Overridepublicintcompare(Integer k1,Integer k2) { // Compare value by frequency int freqCompare =freqMap.get(k2).compareTo(freqMap.get(k1)); // Compare value if frequency is equal int valueCompare =k1.compareTo(k2); // If frequency is equal, then just compare by value, otherwise - // compare by the frequency. if (freqCompare ==0) return valueCompare; elsereturn freqCompare; } }