205. Isomorphic Strings

  • Difficulty: Easy

  • Topics: Hash Table

  • Similar Questions:

Problem:

Given two strings s and t, determine if they are isomorphic.

Two strings 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:

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

Example 2:

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

Example 3:

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

Note:
You may assume both and have the same length.

Solutions:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, char> s2t;
        unordered_map<char, char> t2s;

        if (s.length() != t.length())   return false;
        for (int i = 0; i < s.length(); ++i) {
            if (s2t.count(s[i]) > 0) {
                if (s2t[s[i]] != t[i] || t2s.count(t[i]) == 0 || t2s[t[i]] != s[i])  return false;
            } else {
                if (t2s.count(t[i]) > 0)  return false;
                s2t[s[i]] = t[i];
                t2s[t[i]] = s[i];
            }
        }

        return true;
    }
};

results matching ""

    No results matching ""