Isomorphic Strings Problem


Description

LeetCode Problem 205.

Given two strings s and t, determine 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 1:

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

Example 2:

1
2
Input: s = "foo", t = "bar"
Output: false

Example 3:

1
2
Input: s = "paper", t = "title"
Output: true

Constraints:

  • 1 <= s.length <= 5 * 10^4
  • t.length == s.length
  • s and t consist of any valid ascii character.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        map<char, char> replaced;
        map<char, char> reverse_replaced;
        map<char, char>::iterator mit1, mit2;
        
        if (s.size() != t.size())
            return false;
        
        for (int i = 0; i < s.size(); i ++) {
            mit1 = replaced.find(s[i]);
            mit2 = reverse_replaced.find(t[i]);
            
            if ((mit1 == replaced.end()) && (mit2 == reverse_replaced.end())) {
                replaced.emplace(s[i], t[i]);
                reverse_replaced.emplace(t[i], s[i]);
                s[i] = t[i];
            } else if ((mit1 == replaced.end()) && (mit2 != reverse_replaced.end())) {
                return false;
            } else if ((mit1 != replaced.end()) && (mit2 == reverse_replaced.end())) {
                return false;
            } else {
                if ((t[i] != mit1->second) || (s[i] != mit2->second))
                    return false;
                s[i] = t[i];
            }

        }
        if (s != t)
            return false;
        else 
            return true;
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...