leetcode 290. Word Pattern
来源:互联网 发布:电脑群控软件 编辑:程序博客网 时间:2024/06/05 16:26
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.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
给你一个匹配模式,如果给定的字符串符合这个模式,则为true,否则为false
利用两个哈希表完成,需要考虑到一些边界条件。
两个哈希表,分别存放左边的字符和右边的字符串,以及右边的字符串和左边的字符,判断匹配的时候,两个都查询一下。
import java.util.*;class Solution { public boolean wordPattern(String pattern, String str) { if(!str.contains(" ")){ if(pattern.equals(str)){ if(str.length()==1&&pattern.length()==1) return true; else return false; }else{ if(pattern.length()==1) return true; return false; } } String [] strs = str.split(" "); if(strs.length!=pattern.length()){ return false; } Map<String,String> map = new HashMap<String,String>(); Map<String,String> map2 = new HashMap<String,String>(); for(int i=0;i<pattern.length();i++){ String ss = pattern.charAt(i)+"" ; String aa = map.get(ss); if(map.containsKey(ss)&&!aa.equals(strs[i])){ return false; }else if(!map.containsKey(pattern.charAt(i)+"")&&!map2.containsKey(strs[i])){ map.put(ss,strs[i]); map2.put(strs[i],ss); }else if(!map.containsKey(ss)&&map2.containsKey(strs[i])){ return false; } } return true; }}
阅读全文
0 0
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern LeetCode
- Leetcode 290. Word Pattern
- 【LeetCode】290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- leetcode 290. Word Pattern
- LeetCode 290. Word Pattern
- LeetCode 290. Word Pattern
- [leetcode] 290. Word Pattern
- 【LeetCode】290. Word Pattern
- LeetCode-290.Word Pattern
- Leetcode 290. Word Pattern
- leetcode:290. Word Pattern
- 290.[Leetcode]Word Pattern
- [Leetcode]290. Word Pattern
- LeetCode 290. Word Pattern
- 职业生涯指南——附神级跳槽攻略图!
- 工作中 最让程序员生气的十件事情
- 支撑程序员的三种精神
- ecshop文件夹权限
- angualar $http vs $resource
- leetcode 290. Word Pattern
- vim卡顿及解决方式
- Leetcode 83-Remove Duplicates from Sorted List
- C++中两个类互相引用的解决方法
- 抽取式文档摘要方法(二)
- Eclipse 调试出现source not found问题
- pickle用法
- Git安装配置
- 设计模式之适配器模式与外观模式