Look a hundred times beauty, beauty is not necessarily yours. But if you run the algorithm a hundred times, the knowledge is yours

Who can have nine floors? No need to get up!

Title address

The title

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, in theabcdSwap subscripts in0And the subscript2The element can be generatedcbad.

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

Tip:

  • 1 <= s.length, goal.length <= 2 * 104
  • sandgoalConsists of lowercase English letters

Their thinking

  • ifsandgoalDifferent in length orsThe length is only1And for thefalse
  • ifs===goal, thensIf there are repeated elements in”
  • ifs! =goal,sandgoalThere can only be two different elements, and the elements must be the same when swapped

This intimate string is not at all intimate 👀 ha ha ~😆

The problem solving code

var buddyStrings = function(s, goal) {
    if(s.length! =goal.length||s.length==1) return false
    if(s==goal){
        let arr = s.split(' ')
        arr = Array.from(new Set(arr))
        returns.length! = arr.length }let flag = false
    let arr = []
    for(let i in s){
        if(s[i]! =goal[i]) arr.push(i) }if(arr.length! =2) return false
    let [a,b]= arr
    return s[a]==goal[b]&&s[b]==goal[a]
};
Copy the code

If you have any questions or suggestions, please leave a comment!