Skip to content

859. Buddy Strings

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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]];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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));
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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]