第75题 Isomorphic Strings

来源:互联网 发布:美国农业部报告 数据 编辑:程序博客网 时间:2024/05/21 09:11

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.

Hide Tags
 Hash Table
















Solution in C++: 双向hashtable
class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.size()!=t.size()) return false;        int idx=0;        map<char, char> mp, rev_mp;        map<char, char>::iterator it;        while(idx<s.size()){            it = mp.find(s[idx]);            if(it!=mp.end()){                char cur = it->second;                if(t[idx]!=cur) return false;            }            else{                it = rev_mp.find(t[idx]);                if(it!=rev_mp.end()) return false;                mp[s[idx]] = t[idx];                rev_mp[t[idx]] = s[idx];            }            idx++;        }        return true;    }};


0 0