-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringclose.java
37 lines (30 loc) · 968 Bytes
/
stringclose.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
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) {
return false;
}
int[] freq1 = new int[26];
int[] freq2 = new int[26];
for (char c : word1.toCharArray()) {
freq1[c - 'a']++;
}
for (char c : word2.toCharArray()) {
freq2[c - 'a']++;
}
// Check if both words have the same set of unique characters
for (int i = 0; i < 26; i++) {
if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {
return false;
}
}
// Sort the frequency arrays and compare them
Arrays.sort(freq1);
Arrays.sort(freq2);
for (int i = 0; i < 26; i++) {
if (freq1[i] != freq2[i]) {
return false;
}
}
return true;
}
}