Swapping positions

You are given two strings and t of length n. You can select any two positions (can be from the same or different strings) and swap the characters at those two positions. You have to perform this operation exactly once in such a way that there exists a maximum of one position 

i (1in) such that si!=ti
Determine whether it is possible to perform the operation such that the given condition holds or not.

Example:

Input: n = 8, s = "mrxismrx"; string t = "mryismry"
Output: YES

Approach

C++

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

void swappingPositions(int nstring sstring t)
{
    int count = 0swap = 0;

    int c[26] = {0};

    for (int i = 0i < ni++)
    {
        if (s[i] != t[i])
        {
            c[s[i] - 'a']++;
            c[t[i] - 'a']++;
            count++;
        }
    }
    for (int i = 0i < 26i++)
    {
        if (c[i] % 2 <= 1)
        {
            count -= c[i] / 2;
            swap += c[i] / 2;
        }
    }
    if (count <= 1 && swap <= 2)
    {
        cout << "YES\n";
    }
    else
    {
        cout << "NO\n";
    }
}
int main()
{
    int n = 8;
    string s = "mrxismrx";
    string t = "mryismry";

    swappingPositions(nst);

    return 0;
}


No comments:

Post a Comment