Word Pattern问题及解法
来源:互联网 发布:软件开发和软件研发 编辑:程序博客网 时间:2024/06/06 18:23
问题描述:
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
.
- 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.
利用hashtable,将pattern中的每个字符映射成int,str的每个单词同样也映射成int,两者对比,若有映射不相同的,即视为不匹配。
过程详见代码:
class Solution {public: bool wordPattern(string pattern, string str) { map<char,int> p2i; map<string,int> w2i; istringstream in(str); int i = 0, n = pattern.size(); for(string word; in >> word; i++) { if(i == n || p2i[pattern[i]] != w2i[word]) return false; p2i[pattern[i]] = w2i[word] = i + 1;}return i == n; }};
0 0
- Word Pattern问题及解法
- Word Search问题及解法
- Word Ladder问题及解法
- Word Break问题及解法
- Repeated Substring Pattern问题及解法
- Length of Last Word问题及解法
- Longest Word in Dictionary问题及解法
- leetcode[Word Pattern]//待整理多种解法
- Maximum Product of Word Lengths 问题及解法
- Longest Word in Dictionary through Deleting问题及解法
- Heaters问题及解法
- Permutations问题及解法
- Combinations问题及解法
- Subsets问题及解法
- Triangle问题及解法
- Minesweeper问题及解法
- Two Sum问题及解法
- Reverse Integer问题及解法
- 防止一个类被继承
- NYOJ37回文字符串
- request.setCharacterEncoding 、response.setContentType、response.setCharacterEncoding
- 如何使用MongoDB+Springboot实现分布式ID?
- golang学习笔记之引用类型与值类型
- Word Pattern问题及解法
- GitGUI GitBash 推送(push) 403 的解决办法
- 求一个数,从这个数往左起第一个比他小的下标,O(1)复杂度
- VTk显示样式设置
- Android界面生成流程:View的绘制(Draw)
- 蓝桥杯---C语言凑算式(递归全排列、暴力)
- 2017-04-03日志
- Next Greater Element I(在数组中找到比给定数大的下一个数)
- Python入门(十一)File文件方法