word pattern
2016-07-05 08:24
218 查看
Given a
find if
Here follow means a full match, such that there is a bijection between a letter in
a non-empty word in
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
You may assume
lowercase letters separated by a single space.
思路:题目要求保持一一对应的关系,那就用两个hashmap保存住一一对应关系,然后每次循环检测是否对应即可。否则return false
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.
思路:题目要求保持一一对应的关系,那就用两个hashmap保存住一一对应关系,然后每次循环检测是否对应即可。否则return false
public class Solution { public boolean wordPattern(String pattern, String str) { if(pattern == null && str == null) return true; if(pattern == null || str == null) return false; String[] strs = str.split(" "); if(strs.length != pattern.length()) return false; HashMap<Character, String> ptos = new HashMap<Character, String>(); HashMap<String, Character> stop = new HashMap<String, Character>(); for(int i=0; i<strs.length; i++){ char c = pattern.charAt(i); if(ptos.containsKey(c)){ if(!ptos.get(c).equals(strs[i])){ return false; } } else { ptos.put(c, strs[i]); } if(stop.containsKey(strs[i])){ if(stop.get(strs[i]) != c){ return false; } } else { stop.put(strs[i],c); } } return true; } }
相关文章推荐
- 设计模式(3)-结构型-代理模式(proxy)以及java动态代理的两种方式
- 设计模式(3)-结构型-代理模式(proxy)以及java动态代理的两种方式
- 设计模式(3)-结构型-代理模式(proxy)以及java动态代理的两种方式
- 设计模式(3)-结构型-代理模式(proxy)以及java动态代理的两种方式
- 喷水装置(二)
- 勾股定理一日一证连载43
- bzoj 3480 [Usaco2014 Mar]Mooo
- netty websocket协议开发
- windows下Mysql5.6的安装
- VE
- LAMP--2.Apache 编译安装
- printf(“\n c=%d”,c);的意思是这样的 “”中的是要输出的东西,\n是输出时换行,c=原样输出 ,%d就是你输出的后面的变量C是以整形的形式输出的
- 请问printf("%d\r\n",i)与printf("%d\n“)有什么区别,这两句都实现了数据的打印与换行
- 正则表达式与SQL笔记
- 转圈游戏(codevs 3285)
- Android精品课程—PullToRefresh 下拉刷新
- 07.05C
- 什么叫“证明”
- php中使用include(require)嵌套包含文件时的一些注意问题
- NYOJ 228 士兵杀敌(五) (巧用数组)