LeetCode Solutions

859. Buddy Strings

Time:

Space:

			

class Solution {
 public:
  bool buddyStrings(string A, string B) {
    if (A.length() != B.length())
      return false;
    if (A == B && set<char>(begin(A), end(A)).size() < A.length())
      return true;

    vector<int> diff;

    for (int i = 0; i < A.length(); ++i)
      if (A[i] != B[i])
        diff.push_back(i);

    return diff.size() == 2 && A[diff[0]] == B[diff[1]] &&
           A[diff[1]] == B[diff[0]];
  }
};
			

class Solution {
  public boolean buddyStrings(String A, String B) {
    if (A.length() != B.length())
      return false;
    if (A.equals(B)) {
      Set<Character> set = new HashSet<>();
      for (char c : A.toCharArray())
        set.add(c);
      return set.size() < A.length();
    }

    List<Integer> diff = new ArrayList<>();

    for (int i = 0; i < A.length(); ++i)
      if (A.charAt(i) != B.charAt(i))
        diff.add(i);

    return diff.size() == 2 &&
           A.charAt(diff.get(0)) == B.charAt(diff.get(1)) &&
           A.charAt(diff.get(1)) == B.charAt(diff.get(0));
  }
}
			

class Solution:
  def buddyStrings(self, A: str, B: str) -> bool:
    if len(A) != len(B):
      return False
    if A == B and len(set(A)) < len(A):
      return True

    diff = [(a, b) for a, b in zip(A, B) if a != b]

    return len(diff) == 2 and diff[0] == diff[1][::-1]