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表示同質(zhì),對(duì)string來(lái)說(shuō),就是結(jié)構(gòu)相同,里面的字母是誰(shuí)不重要,比如:abb和cdd就是isomorphic,因?yàn)樾问缴鲜且粯拥摹H绾闻袛嗄兀?2. 略微思考,有點(diǎn)沒(méi)有眉目,開(kāi)始有點(diǎn)細(xì)微的緊張。不過(guò)還好,做得多了,有底氣了,和這些情緒都相處得很好。回到正題,兩個(gè)string同時(shí)遍歷,例如:”paper”, “title”,把p映射成t,a映射成i,第二次遇到p時(shí),就查詢之前p映射的是多少,和現(xiàn)在打算映射的值是否一致。如果能通過(guò)所有一致性檢查,說(shuō)明就是isomorphic的;中間任何地方不一致,就不是! 3. 代碼第一次寫(xiě)的時(shí)候,默認(rèn)只用一個(gè)unordered_map來(lái)存s[i]->t[i]的映射,但是對(duì)”agg”和”ggg”則不正確了,還需要存t[i]->s[i]的映射,因?yàn)橹挥羞@個(gè)映射,a和g映射成g都是合法的,但題目要求,不允許兩個(gè)字母映射成一個(gè)字母。因此需要兩個(gè)map來(lái)保存相互的映射關(guān)系最保險(xiǎn)!
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; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注