leetcode: Word Pattern
来源:互联网 发布:金手指炒股软件下载 编辑:程序博客网 时间:2024/06/05 19:55
原题:
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.
题意为给定一个模式串pattern和待匹配的串str,要判断str的模式是否与pattern匹配。
注意点:
- pattern中字符的个数与str中对应字符串个数相等。
- pattern中不相同的字符,在str中对应的字符串也不相等。
由映射关系可知此题需用到map,时间复杂度为O(n),为方便进行匹配判断,可将str划分成数组
public boolean wordPatern(String pattern,String str){ Map<Character,String> mp = new HashMap<Character,String>(); String[] array = str.split(" "); if(pattern.length()!=array.length)return false;//注意点1 for (int i = 0; i < pattern.length(); i++) { if(!mp.containsKey(pattern.charAt(i))){ if(mp.containsValue(array[i])) return false;//注意点2 mp.put(pattern.charAt(i),array[i]); } else if(!mp.get(pattern.charAt(i)).equals(array[i])){ return false; } } return true; }
0 0
- leetcode | Word Pattern
- 【leetcode】290. Word Pattern
- leetcode 290: Word Pattern
- [Leetcode]Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- 【leetcode】290. Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- LeetCode 2 Word Pattern
- leetcode word-pattern
- leetcode: Word Pattern
- leetcode:Word Pattern
- [Leetcode]Word Pattern
- LeetCode Word Pattern
- LeetCode-Word Pattern
- LeetCode:Word Pattern
- leetcode之Word Pattern
- LeetCode题解:4. Median of Two Sorted Arrays
- ln 命令使用参数详解(ln -s 软链接)
- ffmpeg compile
- Microsoft HoloLens 技术解谜(上)
- 图片搜索网站大全
- leetcode: Word Pattern
- Cesium(三) 几何图形与外观
- 装饰者模式
- 工作思维定位,PDCA循环
- Microsoft HoloLens 技术解谜(下)
- maven项目发布到tomcat后没有lib文件夹解决办法
- C语言学习-顺序结构+运算符选讲
- Service的生命周期
- 九度OJ 1041 简单排序