溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

leetCode 205. Isomorphic Strings 哈希 字符串相似

發(fā)布時(shí)間:2020-08-10 20:47:01 來源:網(wǎng)絡(luò) 閱讀:912 作者:313119992 欄目:編程語言

205. 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.

題目大意:

判斷兩個(gè)字符串是否相似。

思路:

使用雙map來進(jìn)行比較。map鍵為字符串元素,值為字符上一次出現(xiàn)的位置。

代碼如下:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.size() != t.size())
            return false;
        unordered_map<char,int> maps;
        unordered_map<char,int> mapt;
        for(int i = 0;i < s.size();i++)
        {
            if(maps.find(s[i]) == maps.end() && mapt.find(t[i]) == mapt.end())
            {
                maps.insert(pair<char,int>(s[i],i));
                mapt.insert(pair<char,int>(t[i],i));
            }
            else if(maps.find(s[i]) != maps.end() && mapt.find(t[i]) != mapt.end())
            {
                if(maps[s[i]] != mapt[t[i]])
                    return false;
                else
                {
                    maps[s[i]] = i;
                    mapt[t[i]] = i;
                }
            }
            else
                return false;
        }
        return true;
    }
};

2016-08-13 17:15:21

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI