1. 程式人生 > >[LeetCode] Isomorphic Strings 同構字串

[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 "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.

這道題讓我們求同構字串,就是說原字串中的每個字元可由另外一個字元替代,可以被其本身替代,相同的字元一定要被同一個字元替代,且一個字元不能被多個字元替代,即不能出現一對多的對映。根據一對一對映的特點,我們需要用兩個雜湊表分別來記錄原字串和目標字串中字元出現情況,由於ASCII碼只有256個字元,所以我們可以用一個256大小的陣列來代替雜湊表,並初始化為0,我們遍歷原字串,分別從源字串和目標字串取出一個字元,然後分別在兩個雜湊表中查詢其值,若不相等,則返回false,若相等,將其值更新為i + 1,因為預設的值是0,所以我們更新值為i + 1,這樣當 i=0 時,則對映為1,如果不加1的話,那麼就無法區分是否更新了,程式碼如下:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int m1[256] = {0}, m2[256] = {0}, n = s.size();
        for (int i = 0; i < n; ++i) {
            if (m1[s[i]] != m2[t[i]]) return false;
            m1[s[i]] = i + 1;
            m2[t[i]] = i + 1;
        }
        
return true; } };

類似題目:

參考資料: