Link Search Menu Expand Document

205. Isomorphic Strings

Solution Code

C#

public class Solution {
    public bool IsIsomorphic(string s, string t) {
        int len = s.Length;
        bool isIso = true;
        int[] mapping = new int[130];
        int[] mappedTo = new int[130];
        
        for (int i = 0; i < len; i++) {
            if (mapping[s[i]] > 0) {
                int val = mapping[s[i]];
                
                if ((int)t[i] != val) {
                    isIso = false;
                    break;
                }
            } else {
                if (mappedTo[t[i]] > 0) {
                    isIso = false;
                    break;
                }
                
                mapping[s[i]] = t[i];
                mappedTo[t[i]] = s[i];
            }
        }
        
        return isIso;
    }
}

C++

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len = s.size();
        bool isIso = true;
        unordered_map<char, char> mapping;
        unordered_map<char, char> mappedTo;
        
        for (int i = 0; i < len; i++) {
            if (mapping.count(s[i])) {
                char ch = mapping[s[i]];
                
                if (t[i] != ch) {
                    isIso = false;
                    break;
                }
            } else {
                if (mappedTo.count(t[i])) {
                    isIso = false;
                    break;
                }
                
                mapping[s[i]] = t[i];
                mappedTo[t[i]] = s[i];
            }
        }
        
        return isIso;
    }
};

Java

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int len = s.length();
        boolean isIso = true;
        int[] mapping = new int[130];
        int[] mappedTo = new int[130];
        
        for (int i = 0; i < len; i++) {
            if (mapping[s.codePointAt(i)] > 0) {
                int val = mapping[s.codePointAt(i)];
                
                if (t.codePointAt(i) != val) {
                    isIso = false;
                    break;
                }
            } else {
                if (mappedTo[t.codePointAt(i)] > 0) {
                    isIso = false;
                    break;
                }
                
                mapping[s.codePointAt(i)] = t.codePointAt(i);
                mappedTo[t.codePointAt(i)] = s.codePointAt(i);
            }
        }
        
        return isIso;
    }
}

© 2023. All rights reserved.

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy