Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 843 Bytes

1247. 交换字符使得字符串相同.md

File metadata and controls

36 lines (29 loc) · 843 Bytes
  • 分组讨论
/**
 *
 * @description
 * @see https://leetcode-cn.com/problems/minimum-swaps-to-make-strings-equal/solution/java-tan-xin-suan-fa-xiang-jie-zhi-xing-yong-shi-n/
 * @param {string} s1
 * @param {string} s2
 * @return {*}  {number}
 */
function minimumSwap(s1: string, s2: string): number {
    let xyCount: number = 0,
        yxCount: number = 0;

    for (let i = 0; i < s1.length; ++i) {
        if (s1[i] === s2[i]) {
            continue;
        }
        s1[i] == 'x' ? ++xyCount : ++yxCount;
    }

    if ((xyCount + yxCount) & 1) {
        return -1;
    }

    if (xyCount & 1) {
        return (xyCount >>> 1) + (yxCount >>> 1) + 2;
    }

    return xyCount / 2 + yxCount / 2;
};