We need to write a method that generates int[] , each value of which will correspond to the position of the letter of a particular word ( String , we will transfer to this method) relative to the alphabet, i.e. need to get something like this:

 SOMEWORDS | 743295618 STAR | 3412 LETTER | 314526 

D - The first letter (relative to the alphabet) in the word → _ _ _ _ _ _ _ 1 _
E - second → _ _ _ 2 _ _ _ 1 _
M - third → _ _ 3 2 _ _ _ 1 _
etc.

If the letters are repeated, the first one that is included in the word is numbered first.

In the code below, I tried to get rid of duplicate characters and sort the string (suggested by enSO), but, having done this, I realized that I don’t understand anything and don’t know what to do next:

 TreeSet<Character> keyTreeSet = new TreeSet<Character>(); for (int i = 0; i < keywordArray.length; i++) { keyTreeSet.add(keyword.charAt(i)); } Iterator iterator; iterator = keyTreeSet.iterator(); StringBuilder s = new StringBuilder(); while (iterator.hasNext()) { s.append(iterator.next()); } 

    1 answer 1

    Head-on solution working for O(n^2) .
    N times (where N is the length of the string) go through the string and look for a symbol with the minimum code among those not yet used (for which the value is not stored in the array), then save the iteration number in the cell whose index coincides with the index of the found symbol with minimum code:

     private static int[] getNumbers(String str) { int[] numbers = new int[str.length()]; for (int i = 1; i <= str.length(); i++) { int min = Integer.MAX_VALUE; int indexOfMin = 0; for (int j = 0; j < str.length(); j++) { if (numbers[j] == 0) { int c = (int)str.charAt(j); if (c < min) { min = c; indexOfMin = j; } } } numbers[indexOfMin] = i; } return numbers; } 
    • It works ... Incredible! I am extremely grateful to you! - Kirill Demidov
    • @KirillDemidov on health. If you are satisfied with the answer, do not forget to mark it as correct (checkmark to the left of the answer). The solution is, in fact, quite simple. Perhaps there are more clever solutions. - Regent