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

public bool IsIsomorphic(string s, string t)
    {
        Hashtable table = new Hashtable();
        HashSet<char> set = new HashSet<char>();
        for (int i = 0; i < s.Length; i++)
        {
            if (table.Contains(s[i]))
            {
                if ((char)table[s[i]] != t[i])
                    return false;
            }
            else
            {
                if (!set.Add(t[i]))
                    return false;
                table.Add(s[i], t[i]);
            }
        }
        return true;
    }

public bool IsIsomorphic(string s, string t)
    {
        int[] ss = new int[256];
        int[] tt = new int[256];
        for (int i = 0; i < s.Length; i++)
        {
            if (ss[s[i]] != tt[t[i]]) return false;
            ss[s[i]] = tt[t[i]] = i + 1;
        }
        return true;
    }


你可能感兴趣的:(LeetCode,hash)