Skip to content

Commit dbade12

Browse files
authored
Merge pull request #623 from ishikasinha-d/isomorphic-strings
Create isomorphic_strings.cpp
2 parents 8b92235 + 0040809 commit dbade12

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Strings/isomorphic_strings.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Given two strings, check if these two strings are isomorphic to each other.
2+
// Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2.
3+
4+
#include<bits/stdc++.h>
5+
#define fl(i,a,b) for(i=a;i<b;i++)
6+
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
7+
using namespace std;
8+
typedef long long int ll;
9+
10+
bool areIsomorphic(string str1, string str2)
11+
{
12+
// strings with unequal lengths cannot be isomorphic
13+
if(str1.length()!=str2.length())
14+
return false;
15+
16+
// for counting frequencies of each character in both the srrings
17+
int str1_freq[256]={0};
18+
int str2_freq[256]={0};
19+
20+
for (int i=0; i< str1.length(); i++)
21+
{
22+
str1_freq[str1[i]]++;
23+
str2_freq[str2[i]]++;
24+
25+
// the moment frequencies of current element in both the strings become unequal, we know that they are not isomorphic
26+
if (str1_freq[str1[i]]!= str2_freq[str2[i]])
27+
return false;
28+
}
29+
30+
return true;
31+
32+
}
33+
34+
int main()
35+
{
36+
fast;
37+
38+
int t;
39+
cin>>t;
40+
string str1,str2;
41+
while (t--)
42+
{
43+
cin>>str1;
44+
cin>>str2;
45+
46+
if(areIsomorphic(str1,str2))
47+
cout<<str1<<" and "<<str2<<" are Isomorphic Strings "<<endl;
48+
else
49+
cout<<str1<<" and "<<str2<<" are not Isomorphic Strings "<<endl;
50+
}
51+
return 0;
52+
}

0 commit comments

Comments
 (0)