205. Isomorphic Strings

来源:互联网 发布:设数组array由以下 编辑:程序博客网 时间:2024/05/22 09:38

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.

Subscribe to see which companies asked this question

solution:

class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.size() != t.size()) return false;        else if(s.empty()) return true;        else{            map<char, char> m,n;            int i = 0;            while(i<s.size()){                auto ret = m.insert(make_pair(s[i],t[i]));                auto ret2 = n.insert(make_pair(t[i],s[i]));                if(ret.second&&ret2.second) i++;                else {                    if((!ret.second&&m[s[i]]==t[i])||(!ret2.second&&n[t[i]]==s[i])) i++;                    else return false;                }            }            return true;        }    }};
自评:运行时间较长,有待改进

0 0