# Isomorphic Strings in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have two strings s and t; we have to check whether they are isomorphic or not. Two strings are said to be isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

So, if the input is like s = "egg", t = "add”, then the output will be true, as e can map to a, and g can map to d.

To solve this, we will follow these steps −

• Define an array arr of size 256 and fill with -1

• Define an array visited of size 256 and fill with 0

• Define an array visited1 of size 256 and fill with 0

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

• if visited[s[i]] is same as 1 or visited1[t[i]] is same as 1, then −

• if arr[s[i]] is not equal to t[i] - ASCII of 'a', then −

• return false

• Otherwise

• visited[s[i]] := 1

• visited1[t[i]] := 1

• arr[s[i]] := t[i] - ASCII of 'a'

• return true

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> arr(256, -1);
vector<bool> visited(256, 0);
vector<bool> visited1(256, 0);
for (int i = 0; i < s.length(); i++) {
if (visited[s[i]] == 1 || visited1[t[i]] == 1) {
if (arr[s[i]] != t[i] - 'a') {
return false;
}
}
else {
visited[s[i]] = 1;
visited1[t[i]] = 1;
arr[s[i]] = t[i] - 'a';
}
}
return true;
}
};
main(){
Solution ob;
cout << (ob.isIsomorphic("sky","fry"));
}

## Input

"sky","fry"

## Output

1