LeetCode.290 Word pattern
来源:互联网 发布:网络攻击的发展趋势是 编辑:程序博客网 时间:2024/06/16 22:16
题目:
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.
class Solution { public boolean wordPattern(String pattern, String str) { //给定字符串和匹配模式,返回是否满足匹配模型 //匹配模式只有一个小些字母表示,字符串的字母由单个空格隔开组成的小写单词 HashMap<String,String> hmP=new HashMap<String,String>(); HashMap<String,String> hmS=new HashMap<String,String>(); int len=0; for(int i=0;i<str.length();i++){ if(str.charAt(i)==' '){ len++; } } if(len+1!=pattern.length())return false; //截断字母串 String [] strs=new String[len+1]; char [] st=str.toCharArray(); int index=0; int count=0; for(int i=0;i<st.length;i++){ if(st[i]==' '||i==st.length-1){ if(i==st.length-1){ //因为截取包左不包右 i++; } strs[count++]=str.substring(index,i); index=i+1; } } char [] pa=pattern.toCharArray(); for(int i=0;i<pattern.length();i++){ char ch=pa[i]; String chStr=String.valueOf(ch); //如果hash表中存在该字符则取出同字母比较 if(hmP.containsKey(chStr)){ if(!hmP.get(chStr).equals(strs[i])){ return false; } }else{ //存在hmT中说明已经匹配过了 if(hmS.containsKey(strs[i])){ return false; } //分别存入对方的 hmP.put(chStr,strs[i]); hmS.put(strs[i],chStr); } } return true; }}
阅读全文
0 0
- 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
- LeetCode 290 Word Pattern
- leetcode 290:Word Pattern
- LeetCode[290] Word Pattern
- Leetcode 290 Word Pattern
- [leetcode][290]Word Pattern
- leetcode-290-Word Pattern
- 130. Surrounded Regions
- 杨辉三角
- python 二维数组的查找
- Caffe从入门到精通03
- 第八周项目三 对称矩阵压缩存储的实现与应用(1)
- LeetCode.290 Word pattern
- Linux下,VMware Tools 安装失败
- 图片水平垂直居中方案
- RecyclerView常用功能解析
- C++实现循环队列
- Leetcode——第88题
- codecademy SQL 编程系列三Create && Insert , Select
- Java作业杨枝10.28/10.29
- 对Servlet的理解