Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Determine Isomorphic Strings in JavaScript



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
Updated on: 2020-11-23T07:08:50+05:30

760 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements