Very simple and readable C# solution with 2 hash maps


  • 1
    A
    public class Solution {
        public bool WordPattern(string pattern, string str) {
            string[] words = str.Split(new char[] {' '});
            
            if (pattern.Length != words.Length) {
                return false;
            }
            
            Dictionary<char, string> mapP2W = new Dictionary<char, string>();
            Dictionary<string, char> mapW2P = new Dictionary<string, char>();
            
            for (int i = 0; i < pattern.Length; i++) {
                if (mapP2W.ContainsKey(pattern[i]) && mapP2W[pattern[i]] != words[i]
                || mapW2P.ContainsKey(words[i]) && mapW2P[words[i]] != pattern[i]) {
                    return false;
                }
                
                mapP2W[pattern[i]] = words[i];
                mapW2P[words[i]] = pattern[i];
            }
            
            return true;
        }
    }

Log in to reply
 

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