天天看點

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

題目解答:判斷兩個單詞是否是同構的。需要兩個map,分别控制s到t和t到s的映射關系。

代碼如下:

class Solution {

public:

    bool isIsomorphic(string s, string t) {

        if(s.length() != t.length())

            return false;

        map<char,char> map_st;

        map<char,char> map_ts;

        for(int i = 0;i < s.length();i++)

        {

            if((map_st.find(s[i]) == map_st.end())|| (map_ts.find(t[i]) == map_ts.end()))

            {

                if(map_st.find(s[i]) != map_st.end())

                    return false;

                else if(map_ts.find(t[i]) != map_ts.end())

                    return false;

                else

                {

                    map_st[s[i]] = t[i];

                    map_ts[t[i]] = s[i];

                }

            }

            else

            {

                if(map_st[s[i]] != t[i])

                    return false;

            }

        }

        return true;

    }

};

轉載于:https://www.cnblogs.com/CodingGirl121/p/5417710.html