Determining isomorphic strings JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Two strings (str1 and str2) are isomorphic if the characters in str1 can be replaced to get str2.

For example −

const str1 = 'abcde';
const str2 = 'eabdc';

These two are an example of isomorphic strings

We are required to write a JavaScript function that in two strings. The function should determine whether or not the two input strings are isomorphic.

Example

const str1 = 'abcde';
const str2 = 'eabdc';
const isIsomorphic = (str1 = '', str2 = '') => {
   if (str1.length !== str2.length) {
      return false;
   };
   for (let i = 0;
   i < str1.length; i++) {
      const a = str1.indexOf(str1[i]);
      const b = str2.indexOf(str2[i]);
      if (str2[a] !== str2[i] || str1[b] !== str1[i]) {
         return false;
      };
   };
   return true;
};
console.log(isIsomorphic(str1, str2));

Output

And the output in the console will be −

true
raja
Published on 23-Nov-2020 07:08:41
Advertisements