LeetCode:Word Pattern
2016-02-02 20:21
417 查看
problem:
Given a
Here follow means a full match, such that there is a bijection between a letter in
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
You may assume
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Solution:
Given a
patternand a string
str, find if
strfollows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in
patternand 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
patterncontains only lowercase letters, and
strcontains lowercase letters separated by a single space.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Solution:
public class Solution { public boolean wordPattern(String pattern, String str) { if (pattern.isEmpty() || str.isEmpty()) { return false; } String[] s = str.split(" "); if (s.length != pattern.length()) { return false; } HashMap<Character, String> hashMap = new HashMap<Character, String>(); for (int i = 0; i < pattern.length(); i++) { if (hashMap.containsKey(pattern.charAt(i))) { if (!hashMap.get(pattern.charAt(i)).equals(s[i])) { return false; } } else if (hashMap.containsValue(s[i])) { return false; } else { hashMap.put(pattern.charAt(i), s[i]); } } return true; } }
相关文章推荐
- 数据库设计
- C#成神之路<6> 数据类型:浮点以及布尔详解
- poj2449 Remmarguts' Date
- IIC 驱动的注册
- 读代码大全2——第五章 软件构建中的设计
- ubuntu 安装 4.4内核版本
- Postgres 9.4 feature highlight: REPLICA IDENTITY and logical replication
- 汇编语言浮点数指令集
- 负载均衡算法
- 学习Discuz! X3.2记录:门户文章模块中为什么看不到文章列表?
- 设计模式总结
- Spark PairRDD 转化二
- POJ1845 Sumdiv(求所有因数和+矩阵快速幂)
- oracle体系结构(图)
- yaourt: a pacman frontend(pacman前端,翻译)
- Robot Framework与Web界面自动化测试学习笔记:如何判断单选框的选中状态
- 在mac 上配置AndroidStudio碰到的坑
- 二叉排序树 2
- 在这里主要讨论脚本运行方式和“命令”运行的方式。环境变量和命令关系
- 看了第二个人的最小生成树的最短路径的差分约束系统