Check if One String Swap Can Make Strings Equal

easy string counting

Problem

You are given two strings s1 and s2 of the same length, both made of lowercase letters. You may perform at most one swap: pick two indices in one of the strings (possibly the same index) and exchange the characters at those positions. Return true if the two strings can be made identical with at most one such swap, and false otherwise.

Inputs1 = "bank", s2 = "kanb"
Outputtrue
The strings differ at indices 0 and 3, and the pairs cross-match ('b'/'k' vs 'k'/'b'), so swapping s1[0] with s1[3] turns "bank" into "kanb".

def are_almost_equal(s1, s2):
    diff = []
    for i in range(len(s1)):
        if s1[i] != s2[i]:
            diff.append(i)
            if len(diff) > 2:
                return False
    if not diff:
        return True
    if len(diff) != 2:
        return False
    i, j = diff
    return s1[i] == s2[j] and s1[j] == s2[i]
function areAlmostEqual(s1, s2) {
  const diff = [];
  for (let i = 0; i < s1.length; i++) {
    if (s1[i] !== s2[i]) {
      diff.push(i);
      if (diff.length > 2) return false;
    }
  }
  if (diff.length === 0) return true;
  if (diff.length !== 2) return false;
  const [i, j] = diff;
  return s1[i] === s2[j] && s1[j] === s2[i];
}
boolean areAlmostEqual(String s1, String s2) {
    List<Integer> diff = new ArrayList<>();
    for (int i = 0; i < s1.length(); i++) {
        if (s1.charAt(i) != s2.charAt(i)) {
            diff.add(i);
            if (diff.size() > 2) return false;
        }
    }
    if (diff.isEmpty()) return true;
    if (diff.size() != 2) return false;
    int i = diff.get(0), j = diff.get(1);
    return s1.charAt(i) == s2.charAt(j)
        && s1.charAt(j) == s2.charAt(i);
}
bool areAlmostEqual(string s1, string s2) {
    vector<int> diff;
    for (int i = 0; i < (int)s1.size(); i++) {
        if (s1[i] != s2[i]) {
            diff.push_back(i);
            if (diff.size() > 2) return false;
        }
    }
    if (diff.empty()) return true;
    if (diff.size() != 2) return false;
    int i = diff[0], j = diff[1];
    return s1[i] == s2[j] && s1[j] == s2[i];
}
Time: O(n) Space: O(1)