leetcode Word Pattern
2015-12-16 11:13
344 查看
Given a
Here follow means a full match, such that there is a bijection between a letter in
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
You may assume
这个题和判断连个字符串是否同构是类似的,会那一道这一道就不成问题了。
只是多了一个字符串分割,我自己写了一个关于字符串分割的函数。除此之外需要构建两个map,一个是map<string,char>一个是map<char,string>
然后就是没有什么难度了,有一个问题就是我在vs2010里mp[pattern[i]]!=v1[i]这句提示不能用“!=”(原来我是没有#include<string>太粗心啦)不过在leetcode的编译器里通过了。
我需要看一下关于字符串的比较。
这是别人这道题分割字符串的方法,学习了:
patternand a string
str, find if
strfollows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in
patternand 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
patterncontains only lowercase letters, and
strcontains lowercase letters separated by a single space.
这个题和判断连个字符串是否同构是类似的,会那一道这一道就不成问题了。
只是多了一个字符串分割,我自己写了一个关于字符串分割的函数。除此之外需要构建两个map,一个是map<string,char>一个是map<char,string>
然后就是没有什么难度了,有一个问题就是我在vs2010里mp[pattern[i]]!=v1[i]这句提示不能用“!=”(原来我是没有#include<string>太粗心啦)不过在leetcode的编译器里通过了。
我需要看一下关于字符串的比较。
class Solution { public: vector<string> splitString(string s){ vector<string> result; string temp; int length=s.length(); for(int i=0;i<length;i++){ if(s[i]!=' '&&i!=length-1) temp+=s[i]; else { if(i==length-1) temp+=s[i]; result.push_back(temp); temp=""; } } return result; } bool wordPattern(string pattern, string str) { vector<string> v1; v1=splitString(str); if(pattern.length()!=v1.size()) return false; map<char,string> mp; for(int i=0;i<pattern.length();i++){ if(mp.find(pattern[i])==mp.end()) mp[pattern[i]]=v1[i]; else if(mp[pattern[i]]!=v1[i]) return false; } map<string,char> mp2; for(int i=0;i<pattern.length();i++){ if(mp2.find(v1[i])==mp2.end()) mp2[v1[i]]=pattern[i]; else if(mp2[v1[i]]!=pattern[i]) return false; } return true; } };
这是别人这道题分割字符串的方法,学习了:
while (sin >> tmp) dic.push_back(tmp); if (dic.size() != pattern.size()) return false;
相关文章推荐
- 注册juery短信,验证码 验证
- GPS卫星信号(三):载波与其调制、解调
- Log4j 日志配置及初始化
- SpringMVC表单标签简介
- c++: allocator, uninitialized_copy, uninitialized_fill_n
- “瀑布流式”图片懒加载代码示例
- 23种设计模式C++实例之组合模式
- PPT分享: Linux启动流程 关于initrd与initramfs的区分及其发展历程
- Label 控件实现跑马灯效果
- oracle 创建小字段索引
- Fatal signal 11 (SIGSEGV) code 1 (SEGV_MAPERR)的解决方案
- Eclipse上GIT插件EGIT使用手册
- Log
- makefile 中变量的赋值
- (三)逻辑运算指令和串操作指令
- 如何用jquery实现点击后跳到页面指定位置
- 实战企业监控Zabbix 2.4.7
- position:fixed ie8兼容性问题
- 浅析okHttp
- ViewPager的setOnPageChangeListener方法详解