Algorithm


Problem Name: 859. Buddy Strings

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 1:

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.

Example 2:

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.

Example 3:

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.

 

Constraints:

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

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    bool buddyStrings(string A, string B) {
        if(A.size() != B.size()) return false;
        int n = A.size(), pos = -1;
        vector<int>count(26);
        bool repeat = false, swaped = false;
        for(int i = 0; i < n; i++){
            if(A[i] != B[i]){
                if(pos == -1) pos = i;
                else if(swaped || A[pos] != B[i] || A[i] != B[pos]> return false;
                else swaped = true;
            }
            if(++count[A[i] - 'a'] > 1) repeat = true;
        }
        return swaped || repeat;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "ab", goal = "ba"

Output

x
+
cmd
true

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean buddyStrings(String s, String goal) {
    if (s.length() != goal.length()) {
      return false;
    }
    if (s.equals(goal)) {
      Set < Character> set = new HashSet<>();
      for (char c : s.toCharArray()) {
        if (set.contains(c)) {
          return true;
        }
        set.add(c);
      }
      return false;
    }
    char[] mismatch = {'-', '-'};
    for (int i = 0; i  <  s.length(); i++) {
      if (s.charAt(i) != goal.charAt(i)) {
        if (mismatch[0] == '|') {
          return false;
        }
        if (mismatch[0] == '-') {
          mismatch[0] = s.charAt(i);
          mismatch[1] = goal.charAt(i);
        } else {
          if (goal.charAt(i) == mismatch[0] && s.charAt(i) == mismatch[1]) {
            mismatch[0] = '|';
            continue;
          }
          return false;
        }
      }
    }
    return mismatch[0] == '|';
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "ab", goal = "ba"

Output

x
+
cmd
true

#3 Code Example with Javascript Programming

Code - Javascript Programming


const buddyStrings = function(A, B) {
    if(A.length !== B.length) return false
    const aCode = ('a').charCodeAt(0)
    if(A === B) {
       const count = new Array(26).fill(0)
       for(let i = 0; i < A.length; i++) {
         count[A.charCodeAt(i) - aCode]++
       }
       for(let el of count> {
         if(el > 1) return true
       }
       return false
    } else {
      const arr = []
      for(let i = 0; i < A.length; i++) {
        if(A[i] !== B[i]) {
           arr.push(i>
           if(arr.length > 2) return false
        }
      }
      if(arr.length !== 2) return false
      return A[arr[0]] === B[arr[1]] && A[arr[1]] === B[arr[0]]
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "ab", goal = "ab"

Output

x
+
cmd
false

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def buddyStrings(self, A, B):
        if len(A) != len(B):
            return False
        dif, dup = [[s1, B[i]] for i, s1 in enumerate(A) if s1 != B[i]], len(A) != len(set(A))
        return len(dif) == 2 and dif[0] == dif[1][::-1] or (not dif and dup)
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "ab", goal = "ab"

Output

x
+
cmd
false

#5 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0859_BuddyStrings
    {
        public bool BuddyStrings(string A, string B)
        {
            if (A.Length != B.Length) return false;
            if (A == B)
            {
                int[] counts = new int[26];
                for (int i = 0; i  <  A.Length; ++i)
                    counts[A[i] - 'a']++;

                foreach (int c in counts)
                    if (c > 1) return true;
                return false;
            }

            int first = -1, second = -1;
            for (int i = 0; i  <  A.Length; ++i)
            {
                if (A[i] != B[i])
                {
                    if (first == -1)
                        first = i;
                    else if (second == -1)
                        second = i;
                    else
                        return false;
                }
            }

            return second != -1 && A[first] == B[second] && A[second] == B[first];
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "aa", goal = "aa"

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#858 Leetcode Mirror Reflection Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#860 Leetcode Lemonade Change Solution in C, C++, Java, JavaScript, Python, C# Leetcode