
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Two Strings can be Made Equal by Swapping from Third String in C++
Suppose we have three strings S, T and U of same length n. For every index i in range 0 to n-1, we must swap U[i] with either S[i] or T[i]. So in total we have performed n swapping operations. We have to check whether after such n operations we can make string S exactly same as T.
So, if the input is like S = "abc"; T = "bca"; U = "bca", then the output will be True, because for all i if we swap U[i] with S[i], it will be "bca", and T is already "bca".
Steps
To solve this, we will follow these steps −
for initialize i := 0, when S[i] is non-zero, update (increase i by 1), do: if S[i] is not equal to U[i] and T[i] is not equal to U[i], then: return false return true
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(string S, string T, string U) { for (int i = 0; S[i]; ++i) if (S[i] != U[i] && T[i] != U[i]) return false; return true; } int main() { string S = "abc"; string T = "bca"; string U = "bca"; cout << solve(S, T, U) << endl; }
Input
"abc", "bca", "bca"
Output
1
Advertisements