Skip to content

Commit 58c0506

Browse files
authored
Create 2531. Make Number of Distinct Characters Equal
1 parent e488d12 commit 58c0506

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public boolean isItPossible(String word1, String word2) {
3+
int[] occ1 = findOccurance(word1);
4+
int[] occ2 = findOccurance(word2);
5+
6+
for(int i=0;i<26;i++){
7+
if(occ1[i]>0){
8+
for(int j=0;j<26;j++){
9+
if(occ2[j]>0){
10+
swap(occ1,occ2,i,j);
11+
if(areDistinctEqual(occ1,occ2)){
12+
return true;
13+
}
14+
swap(occ1,occ2,j,i);
15+
}
16+
}
17+
}
18+
}
19+
return false;
20+
}
21+
22+
private boolean areDistinctEqual(int[] occ1,int[] occ2){
23+
int count=0;
24+
for(int i=0;i<26;i++){
25+
if(occ1[i]>0) count++;
26+
if(occ2[i]>0) count--;
27+
}
28+
return count==0;
29+
}
30+
31+
private void swap(int[] occ1,int[] occ2,int i,int j){
32+
occ1[i]--;
33+
occ2[i]++;
34+
occ1[j]++;
35+
occ2[j]--;
36+
}
37+
38+
private int[] findOccurance(String word){
39+
int[] occurance = new int[26];
40+
for(char c:word.toCharArray()){
41+
occurance[c-'a']++;
42+
}
43+
return occurance;
44+
}
45+
}

0 commit comments

Comments
 (0)