【一天一道LeetCode】#205. Isomorphic Strings

一天一道LeetCode

本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
歡迎轉載,轉載請註明出處

(一)題目

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中的每個字符能個通過某種映射關係得到t,則返回true,否則返回false
解題思路:如題目給的例子,“egg”和“add”,e->a,g->d,通過這個映射關係可以得到add。
所以,很容易想到用hash表來解決這個問題。不過要注意: 不允許s中的兩個不同字符對應t中的同一個字符。
即s = “ab”,t = “aa”,s中a和b不能同時對應t中的a
下面看代碼:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len = s.length();
        if(len==0) return true;
        //必須要雙向映射,避免出現一對多,多對一等情況
        char hash[256];
        char hash2[256];
        memset(hash,' ',256*sizeof(char));
        memset(hash2,' ',256*sizeof(char));
        for(int i = 0 ; i < len ; i++){
            if(hash[s[i]]==' '&&hash2[t[i]]==' '){//如果該組字符沒有映射關係
                hash[s[i]] = t[i];//建立映射關係
                hash2[t[i]] = s[i];
            }
            else {
                if(hash[s[i]]==t[i]&&hash2[t[i]]==s[i]) continue;
                else return false;
            }
        }
        return true;
    }
};
發佈了241 篇原創文章 · 獲贊 52 · 訪問量 57萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章