天天看點

[LeetCode] Isomorphic Strings 同構字元串

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 <code>"egg"</code>, <code>"add"</code>, return true.

Given <code>"foo"</code>, <code>"bar"</code>, return false.

Given <code>"paper"</code>, <code>"title"</code>, return true.

Note:

You may assume both s and t have the same length.

這道題讓我們求同構字元串,就是說原字元串中的每個字元可由另外一個字元替代,可以被其本身替代,相同的字元一定要被同一個字元替代,且一個字元不能被多個字元替代,即不能出現一對多的映射。根據一對一映射的特點,我們需要用兩個哈希表分别來記錄原字元串和目标字元串中字元出現情況,由于ASCII碼隻有256個字元,是以我們可以用一個256大小的數組來代替哈希表,并初始化為0,我們周遊原字元串,分别從源字元串和目标字元串取出一個字元,然後分别在兩個哈希表中查找其值,若不相等,則傳回false,若想等,将其值更新為i + 1,代碼如下:

繼續閱讀