Last active
June 7, 2019 05:06
-
-
Save findli/9f87bf0662fd4782e228dbe878c38294 to your computer and use it in GitHub Desktop.
Alfa Soft test v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dz.alfaSoft; | |
import java.util.*; | |
import java.util.stream.IntStream; | |
/* | |
найти строки состоящие из одинакового набора букв, например строки "aa" и "aaa" - разные | |
"abb" и "bba" и "bab" - одинаковые, исходный массив менять нельзя, | |
результат распечать в виде индексов элементов на консоль, строки без дубликатов - не выводить | |
пример результата для массива из задачи (форматирование может быть любое): | |
abc 0,1,2 | |
d 3,5 | |
et 4,6 | |
*/ | |
public class Test2 { | |
private static final int AMOUNT_LETTERS = 26; | |
public static void main(String[] args) { | |
String[] data = {"abc", "bac", "abc", "d", "et", "d", "et", "zzz"}; | |
final HashMap<String, int[]> res = new HashMap<>(); | |
final int size = data.length; | |
for (int i = 0; i < size; i++) { | |
String word1 = data[i]; | |
for (int j = 0; j < size; j++) { | |
if (!isWordEqual2(word1, data[j])) continue; | |
if (res.containsKey(word1)) { | |
final int[] ints = res.get(word1); | |
int finalJ = j; | |
if (IntStream.of(ints).anyMatch(x -> x == finalJ)) continue; | |
final int[] ints1 = Arrays.copyOf(ints, ints.length + 1); | |
ints1[ints.length] = j; | |
res.put(data[i], ints1); | |
} else { | |
res.put(data[i], new int[]{j}); | |
} | |
} | |
} | |
res.forEach((s, ints) -> System.out.println(s + Arrays.toString(ints))); | |
} | |
// nlogn | |
/*private static boolean isWordEqual(String wordLeft, String wordRight) { | |
final int[] word1 = wordLeft.chars().toArray(); | |
final int[] word2 = wordRight.chars().toArray(); | |
Arrays.sort(word1);// nlogn | |
Arrays.sort(word2); | |
if (word1.length != word1.length) return false; | |
for (int k = 0; k < word1.length; k++) if (word1[k] != word2[k]) return false; | |
return true; | |
}*/ | |
// n | |
private static boolean isWordEqual2(String wordLeft, String wordRight) { | |
final int[] chars1 = getChars(wordLeft); | |
final int[] chars2 = getChars(wordRight); | |
if (chars1.length != chars2.length) return false; | |
for (int i = 0; i < chars1.length; i++) { | |
if (chars1[i] != chars2[i]) return false; | |
} | |
return true; | |
} | |
private static int[] getChars(String str) { | |
int[] array = new int[AMOUNT_LETTERS]; | |
for (int i = 0; i < str.length(); i++) { | |
char ch = str.charAt(i); | |
array[ch - 'a']++; | |
} | |
return array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment