c# solution using Hashtable


  • 0
    X

    public bool WordPattern(string pattern, string str) {

        var patternDict = new Hashtable();        
        string[] words = str.Split(' ');
        
        if (words.Count() != pattern.Length)
        {
            return false;
        }
        
        for(int j=0; j<pattern.Length; j++)
        {
            if ((!patternDict.ContainsKey(pattern[j]) && patternDict.ContainsKey(words[j])) ||
            (patternDict.ContainsKey(pattern[j]) && !patternDict.ContainsKey(words[j])))
            {
                return false;
            }
            else if (!patternDict.ContainsKey(pattern[j]) && !patternDict.ContainsKey(words[j]))
            {
                patternDict[pattern[j]] = j;
                patternDict[words[j]] = j;
            }
            else
            {
                if ((int)patternDict[pattern[j]] != (int)patternDict[words[j]])
                {
                    return false;
                }
            }
        }
        
        return true;
    }

Log in to reply
 

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