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.
[LeetCode Source]
分析:Isomorphic指的是同构词,即s和t中相同位置的词是一一对应的关系。比如“egg","add"。e对应a,g对应d。
注意这种对应关系是相互的。采用两个map就可以解决问题了。
class Solution { public: bool isIsomorphic(string s, string t) { map<char,char> contrast1; map<char,char> contrast2; for(int i=0; i<s.size(); ++i){ if(contrast1.find(s[i])!=contrast1.end()){ if(contrast1[s[i]]!=t[i]||contrast2[t[i]]!=s[i]){ return false; } } else { contrast1[s[i]] = t[i]; if(contrast2.find(t[i])!=contrast2.end()){ if(contrast1[s[i]]!=t[i]||contrast2[t[i]]!=s[i]){ return false; } } else contrast2[t[i]] = s[i]; } } return true; } };