290. Word Pattern

来源:互联网 发布:手机淘宝 国际版 编辑:程序博客网 时间:2024/06/08 09:03

原题

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

pattern = "abba", str = "dog cat cat dog" should return true.pattern = "abba", str = "dog cat cat fish" should return false.pattern = "aaaa", str = "dog cat cat dog" should return false.pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

代码实现

public bool WordPattern(string pattern, string str){            string[] words = str.Split(' ');            if (pattern.Length != words.Length) return false;            //char in pattern maps to word in str            var patternDict = new Dictionary<char, string>();            //word in str maps to char in pattern            var wordsDict = new Dictionary<string, char>();            for (int i = 0; i < pattern.Length; i++){            //key->val: char->word; word->char; unique                 if(patternDict.ContainsKey(pattern[i]) && patternDict[pattern[i]]!=words[i] ||                   wordsDict.ContainsKey(words[i]) && wordsDict[words[i]]!=pattern[i] )                    return false;                patternDict[pattern[i]] = words[i];                wordsDict[words[i]] = pattern[i];            }            return true;        }

leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

2 0