leetcode 290 Word Pattern
2016-01-25 16:32
176 查看
原题:
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.
题意:
给你一个模式串和一个字符串,其中模式串中一个字母代表一种字符串,现在问你字符串和模式串能不能匹配上。
解答:
首先把给的字符串按空格拆开存起来,然后建立两个映射表,一个是模式串中的字符对应于单词,另一个是单词对应模式串里的字符。首先,如果模式串里的字母数和单词的数量不对应那肯定是false,否则判断双向映射是否匹配即可~
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.
题意:
给你一个模式串和一个字符串,其中模式串中一个字母代表一种字符串,现在问你字符串和模式串能不能匹配上。
[code]class Solution { map<char,string> mc; map<string,char> ms; vector<string> vs; public: bool wordPattern(string pattern, string str) { mc.clear(); ms.clear(); vs.clear(); str+=" "; int pos=0; for(int j=0;j<str.size();j++) { if(str[j]==' ') { string tmp=str.substr(pos,j-pos); pos=j+1; vs.push_back(tmp); } } if(vs.size()!=pattern.size()) return false; for(int i=0;i<pattern.size();i++) { char c=pattern[i]; if(mc[c]==""&&ms[vs[i]]==0) { mc[c]=vs[i]; ms[vs[i]]=c; } else { if(mc[c]!=vs[i]||ms[vs[i]]!=c) return false; } } return true; } };
解答:
首先把给的字符串按空格拆开存起来,然后建立两个映射表,一个是模式串中的字符对应于单词,另一个是单词对应模式串里的字符。首先,如果模式串里的字母数和单词的数量不对应那肯定是false,否则判断双向映射是否匹配即可~
相关文章推荐
- zabbix 监控磁盘I/O
- Linux---tar解压报错Child returned status 1
- 给button设置selector
- android 震动的实现
- 手机端图片左右滑动效果实现
- Java nio epoll mina
- winform配置文件的简单使用
- 使用Visual Studio指定命令行参数
- windows7上可以正常安装的VS2010版本
- Windows7远程登陆访问2003很卡的解决办法
- 程序员的工作环境与效率
- 这些习惯很伤肾 要警觉
- tomcat远程调试设置
- 解决mysql出现“the table is full”的问题
- 写代码如坐禅:你是哪一类程序员
- Eclipse中,打开文件所在文件夹的插件,及设置
- 运行tomcat7w.exe tomcat7.exe ,提示 指定的服务未安装 unable to open the service 'tomcat7'
- slave.jar下载地址
- mysql update语句问题:You can't specify target table 'user' for update in FROM clause
- 【转】加快 FlashBuilder4 的编译速度