C# solution - Dictionary


  • 0
    3
    public class Solution {
        public bool WordPattern(string pattern, string str) {
            Dictionary<char,string> dict = new Dictionary<char,string>();
            string[] arr = str.Split(' ');
            char[] patt = pattern.ToCharArray();
            if(arr.Length != patt.Length) return false;
            for(int i = 0; i<arr.Length; i++)
            {
                if(dict.ContainsKey(patt[i]) )
                {
                    if(dict[patt[i]] != arr[i] ) return false;
                }
                else if(dict.ContainsValue(arr[i]))  return false;
                else dict[patt[i]] = arr[i];
            }
            return true;
        }
    }
    

Log in to reply
 

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