2531.使字符串中不同字符的数目相等
链接:2531.使字符串中不同字符的数目相等
难度:Medium
标签:哈希表、字符串、计数
简介:给你两个下标从 0 开始的字符串 word1 和 word2 。如果可以通过 恰好一次 移动,使 word1 和 word2 中不同字符的数目相等,则返回 true ;否则,返回 false 。
题解 1 - typescript
- 编辑时间:2023-01-08
- 执行用时:160ms
- 内存消耗:49MB
- 编程语言:typescript
- 解法介绍:存储后遍历。
const list = new Array(26).fill(0).map((_, i) => String.fromCodePoint(i + 97));
function isItPossible(word1: string, word2: string): boolean {
const map1 = new Map<string, number>();
for (const c of word1) map1.set(c, (map1.get(c) ?? 0) + 1);
const map2 = new Map<string, number>();
for (const c of word2) map2.set(c, (map2.get(c) ?? 0) + 1);
const len1 = map1.size;
const len2 = map2.size;
for (const c1 of list) {
for (const c2 of list) {
if (check(c1, c2)) return true;
}
}
return false;
function check(c1: string, c2: string): boolean {
const cnt1 = map1.get(c1) ?? 0;
const t1 = map1.get(c2) ?? 0;
const cnt2 = map2.get(c2) ?? 0;
const t2 = map2.get(c1) ?? 0;
if (cnt1 === 0 || cnt2 === 0) return false;
if (c1 === c2) return len1 === len2;
if (cnt1 === 1 && cnt2 === 1) {
if (t1 === 0 && t2 === 0) return len1 === len2;
if (t1 === 0 && t2 !== 0) return len1 + 1 === len2;
if (t1 !== 0 && t2 === 0) return len1 === len2 + 1;
if (t1 !== 0 && t2 !== 0) return len1 === len2;
}
if (cnt1 === 1 && cnt2 > 1) {
if (t1 === 0 && t2 === 0) return len1 === len2 + 1;
if (t1 === 0 && t2 !== 0) return len1 === len2;
if (t1 !== 0 && t2 === 0) return len1 - 1 === len2 + 1;
if (t1 !== 0 && t2 !== 0) return len1 - 1 === len2;
}
if (cnt1 > 1 && cnt2 === 1) {
if (t1 === 0 && t2 === 0) return len2 === len1 + 1;
if (t1 !== 0 && t2 === 0) return len2 === len1;
if (t1 === 0 && t2 !== 0) return len2 - 1 === len1 + 1;
if (t1 !== 0 && t2 !== 0) return len2 - 1 === len1;
}
if (cnt1 > 1 && cnt2 > 1) {
if (t1 === 0 && t2 === 0) return len1 === len2;
if (t1 !== 0 && t2 === 0) return len1 === len2 + 1;
if (t1 === 0 && t2 !== 0) return len1 + 1 === len2;
if (t1 !== 0 && t2 !== 0) return len1 === len2;
}
return false;
}
}
题解 2 - rust
- 编辑时间:2023-01-08
- 执行用时:4ms
- 内存消耗:2.3MB
- 编程语言:rust