Check if One String Swap Can Make Strings Equal

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Example :

Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool areAlmostEqual(string s1string s2)
{

    int n = s1.size();

    int i = 0j = n - 1;

    while (i < j)
    {
        if (s1[i] == s2[i])
        {
            i++;
        }
        else
        {
            break;
        }
    }
    while (i < j)
    {
        if (s1[j] == s2[j])
        {
            j--;
        }
        else
        {
            break;
        }
    }

    if (s2[i] == s1[j] && s2[j] == s1[i])
        swap(s2[i]s2[j]);
    else
        return false;

    while (i < j)
    {
        if (s1[i] != s2[i])
            return false;
        else
            i++;
    }
    return true;
}

int main()
{
    string s1 = "bank"s2 = "kanb";

    if (areAlmostEqual(s1s2))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment