[leetcode] Isomorphic Strings


Isomorphic Strings

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.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

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

Use two hash map to guarantee bijection.

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        char map[256], rmap[256];
        memset(map, 0, sizeof(map));
        memset(rmap, 0, sizeof(rmap));
        if(s.size() != t.size()) return false;
        for(int i = 0; i < s.size(); i++){
            if(map[s[i]] == 0 && rmap[t[i]] == 0){
                map[s[i]] = t[i];
                rmap[t[i]] = s[i];
            }else if(map[s[i]] == t[i] && rmap[t[i]] == s[i]){
                continue;
            }else{
                return false;
            }
        }
        return true;
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.