290. Word Pattern

xiaoxiao2021-02-28  97

原题

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

转载请注明原文地址: https://www.6miu.com/read-81760.html

最新回复(0)