Isomorphic Strings

来源:互联网 发布:制作linux启动u盘 编辑:程序博客网 时间:2024/05/22 13:29

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.
思路:两个哈希表,键和值一一对应,同Word Pattern

class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.length() != t.length())            return false;        map<char, char>st;        map<char, char>ts;        int len = s.length();        for(int i = 0; i < len; ++i){            if(!st.count(s[i]))                st.insert(pair<char, char>(s[i], t[i]));            else if(st[s[i]] != t[i])                return false;            if(!ts.count(t[i]))                ts.insert(pair<char, char>(t[i], s[i]));            else if(ts[t[i]] != s[i])                return false;        }        return true;    }};
0 0
原创粉丝点击