C++, using two vectors to map bidirectionally


  • 0
    H
    
    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            if ( s.size() == 0 && t.size() == 0 ) return true;
            
            // map each char in s to those in t
            // f: ascii -> ascii, bijection
            vector<int> f(256, -1);
            vector<int> g(256, -1);
            
            for (int i = 0; i < s.size(); i++) {
                if ( f[s[i]] == -1 ) {
                    f[s[i]] = t[i];
                    if ( g[t[i]] == -1 ) { // check if t[i] is already mapped (injection)
                        g[t[i]] = s[i];
                    }
                    else return false;
                }
                else {
                    if ( f[s[i]] != t[i] ) return false;
                }
            }
            return true;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.