-
Notifications
You must be signed in to change notification settings - Fork 28
/
WordPatternWith2DArrayDemo.java
77 lines (62 loc) · 1.71 KB
/
WordPatternWith2DArrayDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package ds_003_arrays;
public class WordPatternWith2DArrayDemo {
public static void main(String[] args) {
// checkWords("levo", "olev");
checkWords("llvo", "olev");
checkWords("olev", "llvo");
checkWords("levo", "evol");
checkWords("levo", "levol");
}
private static void checkWords(String word1, String word2) {
boolean result = isSameCharactersUsed(word1, word2);
if(result) {
System.out.printf("\"%s\" and \"%s\" has same characters\n", word1, word2);
} else {
System.out.printf("\"%s\" and \"%s\" don't use same characters\n", word1, word2);
}
}
private static boolean isSameCharactersUsed(String word1, String word2) {
if(word1.length() != word2.length()) {
return false;
}
char[] array1 = word1.toCharArray();
char[] array2 = word2.toCharArray();
int[][] patternArray = new int[array1.length][array2.length];
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array2.length; j++) {
if(array1[i] == array2[j]) {
patternArray[i][j]++;
}
}
}
// rows
for(int i = 0; i < patternArray.length; i++) {
int count = 0;
for(int j = 0; j < patternArray[i].length; j++) {
count += patternArray[i][j];
}
if(count != 1) {
return false;
}
}
// columns
for(int i = 0; i < patternArray.length; i++) {
int count = 0;
for(int j = 0; j < patternArray[i].length; j++) {
count += patternArray[j][i];
}
if(count != 1) {
return false;
}
}
return true;
}
public static void print2DArray(int[][] patternArray) {
for(int i = 0; i < patternArray.length; i++) {
for(int j = 0; j < patternArray[i].length; j++) {
System.out.printf("%d ", patternArray[i][j]);
}
System.out.print("\n");
}
}
}