
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Isomorphic Strings in C++
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 −
#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
- Related Articles
- Determining isomorphic strings JavaScript
- Python - Check if two strings are isomorphic in nature
- How to check whether the given strings are isomorphic using C#?
- Check if a Tree is Isomorphic or not in C++
- Finding the simple non-isomorphic graphs with n vertices in a graph
- Formatted Strings Using Template Strings in JavaScript
- Comparing Strings and Portions of Strings in Java
- Differences between Compact Strings and Compressed Strings in Java 9?
- Join Strings in Java
- Strings in C Language
- Updating Strings in Python
- Multiply Strings in C++
- Manipulating Strings in Java.
- Multiline Strings in Perl
- V-Strings in Perl
