Leetcode 290: Word Pattern
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.
1 public class Solution { 2 public bool WordPattern(string pattern, string str) { 3 var strs = str.Split(' '); 4 5 if (pattern.Length != strs.Length) return false; 6 7 var map = new Dictionary<char, string>(); 8 var reverseMap = new Dictionary<string, char>(); 9 10 for (int i = 0; i < pattern.Length; i++) 11 { 12 if (map.ContainsKey(pattern[i])) 13 { 14 if (map[pattern[i]] != strs[i]) return false; 15 } 16 17 if (reverseMap.ContainsKey(strs[i])) 18 { 19 if (reverseMap[strs[i]] != pattern[i]) return false; 20 } 21 22 map[pattern[i]] = strs[i]; 23 reverseMap[strs[i]] = pattern[i]; 24 } 25 26 return true; 27 } 28 }

浙公网安备 33010602011771号