Input: word1 ="ac", word2 ="b"Output: falseExplanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
Input: word1 ="abcc", word2 ="aab"Output: trueExplanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 ="abac" and word2 ="cab", which both have 3 distinct characters.
Input: word1 ="abcde", word2 ="fghij"Output: trueExplanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
We want to check if swapping any character between the two words can make the number of distinct characters in both words equal. By trying all possible swaps and counting distinct characters after each, we can determine if it’s possible.
classSolution {
funisItPossible(word1: String, word2: String): Boolean {
for (c1 in'a'..'z') {
for (c2 in'a'..'z') {
val cnt1 = IntArray(26)
val cnt2 = IntArray(26)
for (ch in word1) cnt1[ch-'a']++for (ch in word2) cnt2[ch-'a']++if (cnt1[c1-'a'] ==0|| cnt2[c2-'a'] ==0) continue cnt1[c1-'a']-- cnt1[c2-'a']++ cnt2[c2-'a']-- cnt2[c1-'a']++val d1 = cnt1.count { it > 0 }
val d2 = cnt2.count { it > 0 }
if (d1 == d2) returntrue }
}
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defisItPossible(self, word1: str, word2: str) -> bool:
for c1 in set(word1):
for c2 in set(word2):
a = list(word1)
b = list(word2)
a[a.index(c1)] = c2
b[b.index(c2)] = c1
if len(set(a)) == len(set(b)):
returnTruereturnFalse