leetcode Word Pattern
2015-12-04 21:30
309 查看
原题链接:https://leetcode.com/problems/word-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.
Description
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: bool wordPattern(string pattern, string str) { unordered_map<string, char> A; unordered_map<char, string> B; size_t p, i, j = 0, n = pattern.length(); for (i = 0; i < n; i++) { char &ch = pattern[i]; p = str.find(' ', j); string ret = str.substr(j, p - j); if (A.find(ret) == A.end()) A[ret] = ch; else if (A[ret] != ch) return false; if (B.find(ch) == B.end()) B[ch] = ret; else if (B[ch] != ret) return false; j = p + 1; } return i == pattern.size() && p == string::npos; } };
相关文章推荐
- 计蒜课—和为M的组合个数
- Openfire on Centos7
- CSS3之position
- poj--1637--Sightseeing tour(网络流,最大流判断混合图是否存在欧拉图)
- 按键精灵V1.0版
- 【练习手记】【多题合集】用树状数组做线段树练习1、2、3
- 开源界何时不再玩捉迷藏游戏?
- project euler 46
- poj--1637--Sightseeing tour(网络流,最大流判断混合图是否存在欧拉图)
- Ubuntu更新数据源
- 解决This function or variable may be unsafe的方法
- qt+opencv3.0配置详解
- project euler 44
- Matlab 最大值滤波 中值滤波 最小值滤波 函数 ordfilt2
- php-redis扩展编译
- 编译时出现clock skew detected, your build may be incompeleted
- 第二个Sprint冲刺事后诸葛亮报告
- C语言命名
- 互联网之殇
- shell编程高级之sed编辑器