알고리즘

Check if One String Swap Can Make Strings Equal

짬뽕얼큰하게 2025. 2. 5. 21:35

Leetcode Problem:

Summary

  • Given two strings of equal length, determine if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings.

Approach

  • This solution works by first finding all the indices where the two strings differ
  • If there are no differences, the strings are already equal, so the function returns true
  • If there are exactly two differences, the function checks if swapping the characters at these indices would result in equal strings
  • If so, the function returns true; otherwise, it returns false.

Complexity

  • O(n), where n is the length of the input strings, because the solution makes a single pass through the strings to find the differences.

Explain

  • The solution uses a vector to store the indices where the two strings differ
  • It then checks if there are exactly two differences
  • If so, it checks if swapping the characters at these indices would result in equal strings by comparing the characters at the two indices in both strings
  • If the characters are the same, the function returns true; otherwise, it returns false.

Solution Code:


class Solution {
public:
    vector diffIdx;
    bool areAlmostEqual(string s1, string s2) {
        for(int i = 0 ; i < s1.size(); i++){
            if(s1[i] != s2[i]){
                diffIdx.push_back(i);
            }
        }
        if(diffIdx.size() == 0) return true;
        if(diffIdx.size() != 2) return false;
        if(s1[diffIdx[0]] != s2[diffIdx[1]]){
            return false;
        }
        if(s1[diffIdx[1]] != s2[diffIdx[0]]){
            return false;
        }
        return true;
    }
};