//给定一个模式和一个字符串str,查找str是否遵循相同的模式。
//给定模式= "abba", str = "dog cat cat dog",返回true。
//给定模式= "abba", str = "dog cat cat fish",返回false。
//给定模式= "aaaa", str = "dog cat cat dog",返回false。
//给定模式= "abba", str = "dog cat cat dog",返回true。
//给定模式= "abba", str = "dog cat cat fish",返回false。
//给定模式= "aaaa", str = "dog cat cat dog",返回false。
//给定模式= "acba", str = "dog fish dog dog",返回false。
思路:建立映射关系,再循环判断
public bool WordPattern(string pattern, string str) { string[] strs = str.Split(' '); if (pattern.Length != strs.Length) return false; Dictionary<char, string> map = new Dictionary<char, string>(); for (int i = 0; i < strs.Length; i++) { string temp; if (map.TryGetValue(pattern[i], out temp)) //存在就判断值是否与map里面得映射一致 { if (temp != strs[i]) return false; //不一致就返回false } else { if (!map.ContainsValue(strs[i])) //如果映射里面不存在这个Key就判断是否存在这个值 { map.Add(pattern[i], strs[i]); //保证value 值唯一 } else //如果存在这个值说明已经存在一个映射了,就返回false { //这个地方特别注意容易忽略 例如如果没有这个else 下面情况就返回true //"acba", str = "dog dog dog dog" 返回true return false; } } } return true; }