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
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern LeetCode
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- Leetcode 290. Word Pattern
- 290. Word Pattern
- 【LeetCode】290. Word Pattern
- 290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- 自定义View圆形进度条
- Java 线程
- 学习目标的层次分类
- Lucene (一)建立索引及应用的属性详解
- 折半查找小程序
- 290. Word Pattern
- leetcode 62-所有可行的路径数
- BNU 51645 ACM Battle【思维+爆搜】确实挺隐秘的一个爆搜题
- java中的一些陷阱
- 系统引导过程概述以&MBR,PBR,BIOS,boot loader各个名词解析
- HDU2602 Bone Collector(01背包)
- hexo从零开始到搭建完整
- 《互联网时代》笔记及观后感
- Oracle coherence 项目常见问题分析