My C# solution by Dictionary


  • 1
    S
    public class Solution {
        public bool WordPattern(string pattern, string str) 
        {
            if(string.IsNullOrEmpty(pattern) && string.IsNullOrEmpty(str))
                return true;
            if(string.IsNullOrEmpty(pattern) || string.IsNullOrEmpty(str))
                return false;
            var ss = str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
            if(ss.Count() != pattern.Length)
                return false;
            var dic = new Dictionary<char, string>();
            for(int i = 0; i<pattern.Length; i++)
            {
                if((dic.ContainsKey(pattern[i]) && dic[pattern[i]] != ss[i]) || (!dic.ContainsKey(pattern[i])&&dic.ContainsValue(ss[i])))
                {
                    return false;
                }
                dic[pattern[i]] = ss[i];
            }
            return true;
        }
    }
    

Log in to reply
 

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