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 s1, string s2){int n = s1.size();int i = 0, j = 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]);elsereturn false;while (i < j){if (s1[i] != s2[i])return false;elsei++;}return true;}int main(){string s1 = "bank", s2 = "kanb";if (areAlmostEqual(s1, s2))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment