---
# System prepended metadata

title: 2531. Make Number of Distinct Characters Equal
tags: [Leetcode, Medium]

---

# 2531. Make Number of Distinct Characters Equal
###### tags: `Leetcode` `Medium`
Link: https://leetcode.com/problems/make-number-of-distinct-characters-equal/description/
## 思路 $O(m+n+26*26)$ $O(26)$
首先记录每个字母出现的次数
然后尝试每一种能换的字母组合
看换完distinct character数目是不是一样的
## Code
```java=
class Solution {
    public boolean isItPossible(String word1, String word2) {
        int[] cnt1 = new int[26];
        int[] cnt2 = new int[26];
        for(int i=0; i<word1.length(); i++){
            cnt1[word1.charAt(i)-'a']++;
        }
        for(int i=0; i<word2.length(); i++){
            cnt2[word2.charAt(i)-'a']++;
        }
        for(int i=0; i<26; i++){
            if(cnt1[i]==0) continue;
            for(int j=0; j<26; j++){
                if(cnt2[j]==0) continue;
                if(equalAfterSwap(i, j, cnt1, cnt2)) return true;
            }
        }
        return false;
    }
    public boolean equalAfterSwap(int c1, int c2, int[] cnt1, int[] cnt2){
        int uni1 = 0, uni2 = 0;
        cnt1[c1]--;
        cnt1[c2]++;
        cnt2[c1]++;
        cnt2[c2]--;
        
        for(int i=0; i<26; i++){
            if(cnt1[i]>0) uni1++;
            if(cnt2[i]>0) uni2++;
        }
        
        cnt1[c1]++;
        cnt1[c2]--;
        cnt2[c1]--;
        cnt2[c2]++;
        return uni1==uni2;
    }
}
```