C# solution using Dictionary


  • 1
    B
    public class Solution {
        public bool IsIsomorphic(string s, string t) {
            
            Dictionary<char, char> map = new Dictionary<char, char>();
            
            for (int i = 0; i < s.Length; i++)
            {
                if (!map.ContainsKey(s[i]))
                {
                    // If the value already exists in the dictionary, return false
                    foreach (KeyValuePair<char, char> isomorph in map)
                    {
                        if (isomorp.Value == t[i]) return false;
                    }
                    
                    // Adding new character mapping
                    map.Add(s[i], t[i]);
                }
                else
                {
                    // If a matching key has a different value, the strings are not isomorphic
                    if (map[s[i]] != t[i]) return false;
                }
            }
            
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.