You are given two strings s 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
such that .
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 n, string s, string t){int count = 0, swap = 0;int c[26] = {0};for (int i = 0; i < n; i++){if (s[i] != t[i]){c[s[i] - 'a']++;c[t[i] - 'a']++;count++;}}for (int i = 0; i < 26; i++){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(n, s, t);return 0;}
No comments:
Post a Comment