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.
s思路: 1. isomorphic表示同質,對string來說,就是結構相同,里面的字母是誰不重要,比如:abb和cdd就是isomorphic,因為形式上是一樣的。如何判斷呢? 2. 略微思考,有點沒有眉目,開始有點細微的緊張。不過還好,做得多了,有底氣了,和這些情緒都相處得很好。回到正題,兩個string同時遍歷,例如:”paper”, “title”,把p映射成t,a映射成i,第二次遇到p時,就查詢之前p映射的是多少,和現在打算映射的值是否一致。如果能通過所有一致性檢查,說明就是isomorphic的;中間任何地方不一致,就不是! 3. 代碼第一次寫的時候,默認只用一個unordered_map來存s[i]->t[i]的映射,但是對”agg”和”ggg”則不正確了,還需要存t[i]->s[i]的映射,因為只有這個映射,a和g映射成g都是合法的,但題目要求,不允許兩個字母映射成一個字母。因此需要兩個map來保存相互的映射關系最保險!
class Solution {public: bool isIsomorphic(string s, string t) { // unordered_map<char,char> mm1,mm2; int i=s.size(); for(int i=0;i<s.size();i++){ if(mm1.count(s[i])){ if(mm1[s[i]]!=t[i]) return false; }else if(mm2.count(t[i])){ if(mm2[t[i]]!=s[i]) return false; } else{ mm1[s[i]]=t[i]; mm2[t[i]]=s[i]; } } return true; }};新聞熱點
疑難解答