[路飞]_每天刷leetcode_14(亲密字符串 buddy strings)

112 阅读1分钟

这是我参与11月更文挑战的第21天,活动详情查看:2021最后一次更文挑战

亲密字符串

LeetCode 传送门859. Buddy Strings

题目

给你两个字符串 s 和 goal ,只要我们可以通过交换 s 中的两个字母得到与 goal 相等的结果,就返回 true ;否则返回 false 。

交换字母的定义是:取两个下标 i 和 j (下标从 0 开始)且满足 i != j ,接着交换 s[i] 和 s[j] 处的字符。

例如,在 "abcd" 中交换下标 0 和下标 2 的元素可以生成 "cbad" 。

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

Example

Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.

Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.

Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.

Input: s = "aaaaaaabc", goal = "aaaaaaacb"
Output: true

Constraints:

  • 1 <= s.length, goal.length <= 2 * 10^4
  • s and goal consist of lowercase letters.

思考线


解题思路

我的第一版。

直接暴力匹配。

/**
 * @param {string} s
 * @param {string} goal
 * @return {boolean}
 */
var buddyStrings = function(s, goal) {
    for(let i = 0; i < s.length; i ++) {
        for(let j = i +1; j < s.length; j ++) {
            const temp = s[i];
            arr = s.split('')
            arr[i] = arr[j];
            arr[j] = temp;
            const n = arr.join('');
            if(n === goal) return true;
        }
    }
    return false;
};

但是这个算法肯定太笨重了,时间复杂度是 O(n^2). 当s长度很大的时候会超时。我们还要继续思考,得出更有效率的算法。

设两个字符串分别为 s 和 goal,其中 s[i]s[i] 表示 s 的第 ii个字符,其中goal[i] 表示goal 的第 i 个字符.根据题意我们可以得出亲密字符的解释

  • 字符串 s 的长度与字符串 goal的长度相等;
  • 存在 i != j,且满足s[i] = goal[j], s[j] = goal[i]。
    • s[i] = s[j]: 则 s[i] = s[j] = goal[i] = goal[j].说明字符串 s 与 goal相等,且我们能够在s中找到两个不同索引 使得s[i] = s[j]
    • s[i] !=s[j]: 说明两个字符串s 与goal 除了 索引 i,j外的字符都是匹配的。

根据以上思路我们可以得到代码:

var buddyStrings = function(s, goal) {
    if (s.length != goal.length) {
        return false;
    }
    
    if (s === goal) {
        const count = new Array(26).fill(0);
        for (let i = 0; i < s.length; i++) {
            count[s[i].charCodeAt() - 'a'.charCodeAt()]++;
            if (count[s[i].charCodeAt() - 'a'.charCodeAt()] > 1) {
                return true;
            }
        }
        return false;
    } else {
        let first = -1, second = -1;
        for (let i = 0; i < s.length; i++) {
            if (s[i] !== goal[i]) {
                if (first === -1)
                    first = i;
                else if (second === -1)
                    second = i;
                else
                    return false;
            }
        }

        return (second !== -1 && s[first] === goal[second] && s[second] === goal[first]);
    }
};