Isomorphic Strings

Given two strings s and tdetermine if they are isomorphic.

Two strings s and t are 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.

Example:

Input: s = "egg", t = "add"
Output: true

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool isIsomorphic(string sstring t)
{
    unordered_map<charcharump;
    for (int i = 0i < s.size(); i++)
    {
        if (ump.find(s[i]!= ump.end())
        {
            if (ump[s[i]] != t[i])
                return false;
        }
        ump[s[i]] = t[i];
    }
    ump.clear();
    for (int i = 0i < t.size(); i++)
    {
        if (ump.find(t[i]!= ump.end())
        {
            if (ump[t[i]] != s[i])
                return false;
        }
        ump[t[i]] = s[i];
    }
    return true;
}

int main()
{
    string s = "egg"t = "add";

    if (isIsomorphic(st))
    {
        cout << "true";
    }
    else
    {
        cout << "false";
    }
    return 0;
}


No comments:

Post a Comment