Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to check if two strings are isomorphic in C++

1 Answer

0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

#include <iostream>
#include <string>
#include <unordered_map>

bool areIsomorphic(const std::string& s, const std::string& t) {
    if (s.size() != t.size()) return false;

    std::unordered_map<char, char> mapST;
    std::unordered_map<char, char> mapTS;

    for (size_t i = 0; i < s.size(); i++) {
        char c1 = s[i], c2 = t[i];

        // Check mapping from s → t
        if (mapST.count(c1)) {
            if (mapST[c1] != c2) return false;
        } else {
            mapST[c1] = c2;
        }

        // Check mapping from t → s
        if (mapTS.count(c2)) {
            if (mapTS[c2] != c1) return false;
        } else {
            mapTS[c2] = c1;
        }
    }
    
    return true;
}

int main() {
    std::cout << std::boolalpha;
    
    std::cout << areIsomorphic("egg", "add") << "\n";  
    std::cout << areIsomorphic("foo", "bar") << "\n";  
    std::cout << areIsomorphic("paper", "title") << "\n";
}



/*
run:

true
false
true

*/

 



answered Dec 18, 2025 by avibootz
edited Dec 19, 2025 by avibootz
...