Topic:

Given two strings s and goal, return true as long as we can get the same result as goal by swapping two letters in S; Otherwise return false. Swap letters are defined by taking two subscripts I and j (subscripts starting at 0) that satisfy I! = j, then swap the characters at s[I] and s[j].

For example, swapping elements with subscripts 0 and 2 in “abcd” can produce “cbad”.

Example 1:

Input: s = "ab", Goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and S [1] = 'b' to produce "BA ", where S and goal are equal.Copy the code

Example 2:

Explanation: You can only swap s[0] = 'a' and S [1] = 'b' to produce "BA ", where S and Goal are not equal.Copy the code

Example 3:

Input: s = "AA ", Goal =" AA "Output: true Explanation: You can swap s[0] = 'a' and S [1] = 'a' to produce" AA ", where S and Goal are equal.Copy the code

Example 4:

Input: s = "aaaaAAABC ", goal =" aaAAAAACb "Output: trueCopy the code

Analysis:

  • Case 1: Two strings are equal and there are duplicate characters in the string, for example
    a b c b abcb
    To exchange repeated characters.
  • Case 2: The two strings differ in only two ways, and
    s [ i ] = g o a l [ j ] ; g o a l [ i ] = s [ j ] s[i] = goal[j]; goal[i] = s[j]
    . That is, the characters of two strings are equal except for the swapped bit characters. If there are more than two differences, it is not true.

Code:

/ * * *@param {string} s
 * @param {string} goal
 * @return {boolean}* /
var buddyStrings = function(s, goal) {
    if(s.length ! == goal.length) {return false;
    }
    
    if (s === goal) {
        let map = {}
        for (let i = 0; i < s.length; i++) {
            map[s[i]] = map[s[i]] ? ++map[s[i]] : 1;
            if (map[s[i]] > 1) {
                return true; }}return false;
    } else {
        let pos1 = -1, pos2 = -1;
        for (let i = 0; i < s.length; i++) {
            if(s[i] ! == goal[i]) {if (pos1 === -1) {
                    pos1 = i;
                } else if (pos2 === -1) {
                    pos2 = i;
                } else {
                    return false; }}}return(pos2 ! = = -1&& s[pos1] === goal[pos2] && s[pos2] === goal[pos1]); }};Copy the code