290. Word Pattern
来源:互联网 发布:linux启动ftp服务 编辑:程序博客网 时间:2024/06/06 01:02
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.
s思路:
1. 由于是一一映射,所以需要两个hash分别负责从pattern->str,str->pattern的映射
2. 另外需要take care of the length consistence. In other words, the two should have the same length.
//方法1:hashclass Solution {public: bool wordPattern(string pattern, string str) { // int n=str.size(); unordered_map<string,string> mm1,mm2; int count=0; for(int i=0;i<str.size();i++){ if(count>=n) return false; if(str[i]==' '){ count++; continue; } int j=i; while(j<str.size()&&str[j]!=' '){ j++; } string cur=str.substr(i,j-i); string p=pattern.substr(count,1); if(mm1.count(cur)&&mm2.count(p)){ if(mm1[cur]!=p&&mm2[p]!=cur) return false; }else if((mm1.count(cur)==0)&&(mm2.count(p)==0)){ mm1[cur]=p; mm2[p]=cur; }else return false; i=j-1; } return count==pattern.size()-1; }};
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern LeetCode
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- Leetcode 290. Word Pattern
- 290. Word Pattern
- 【LeetCode】290. Word Pattern
- 290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- 学习微积分,60年漫漫探索路
- 游戏服务端开发要点
- 19. Remove Nth Node From End of List
- Android应用资源编译打包原理
- 登陆oracle的三种方法
- 290. Word Pattern
- vim moving
- vim separate with . and replace all to end of line
- java多态
- 20. Valid Parentheses
- 292. Nim Game
- vim delete all blank lines
- Leetcode 86. Partition List
- linux count file lines