Program to check we can replace characters to make a string to another string or not in C++

Suppose we have two lowercase strings s and t. Now consider an operation where we replace all occurrences of a character in s with another character. If we can perform this operation any number of times, we have to check whether s can be converted to t or not.

So, if the input is like s = "eye" t = "pip", then the output will be True, as we can replace "e"s with "p"s then "y" by "i".

To solve this, we will follow these steps −

• Define one map m1 and another map m2

• n := size of s

• for initialize i := 0, when i < n, update (increase i by 1), do −

• if s[i] is in m1, then −

• if m1[s[i]] is same as t[i], then −

• go for the next iteration

• return false

• Otherwise

• m1[s[i]] := t[i]

• return true

Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(string s, string t) {
map m1, m2;
int n = s.size();
for(int i = 0; i <n; i++){
if(m1.count(s[i])){
if(m1[s[i]] == t[i]) continue;
return false;
}
else{
m1[s[i]] = t[i];
}
}
return true;
}
int main(){
string s = "eye", t = "pip";
cout << solve(s, t);
}

Input

"eye","pip"

Output

1