-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path2531. Make Number of Distinct Characters Equal
More file actions
45 lines (41 loc) · 1.14 KB
/
2531. Make Number of Distinct Characters Equal
File metadata and controls
45 lines (41 loc) · 1.14 KB
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
class Solution {
public boolean isItPossible(String word1, String word2) {
int[] occ1 = findOccurance(word1);
int[] occ2 = findOccurance(word2);
for(int i=0;i<26;i++){
if(occ1[i]>0){
for(int j=0;j<26;j++){
if(occ2[j]>0){
swap(occ1,occ2,i,j);
if(areDistinctEqual(occ1,occ2)){
return true;
}
swap(occ1,occ2,j,i);
}
}
}
}
return false;
}
private boolean areDistinctEqual(int[] occ1,int[] occ2){
int count=0;
for(int i=0;i<26;i++){
if(occ1[i]>0) count++;
if(occ2[i]>0) count--;
}
return count==0;
}
private void swap(int[] occ1,int[] occ2,int i,int j){
occ1[i]--;
occ2[i]++;
occ1[j]++;
occ2[j]--;
}
private int[] findOccurance(String word){
int[] occurance = new int[26];
for(char c:word.toCharArray()){
occurance[c-'a']++;
}
return occurance;
}
}