290. Word Pattern
2016-05-14 10:35
169 查看
290. Word Pattern
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:
感觉自己的方法比较笨,不过相对自己以前的编码习惯,在按照空格分割string时,引用istringstream的确是一种比较快捷的方法。
解决这个问题的主要思想:
pattern:abba,我们编码为0110;对于pattern中的每个字符,我们将其映射到其第一次出现的位置,这个可以直接利用string的find_first_of得到。
str = “dog cat cat fish”,我们编码为0113;对于vector来说,如何实现将每个单词映射到其第一次出现的位置,我引用了map。
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.
感觉自己的方法比较笨,不过相对自己以前的编码习惯,在按照空格分割string时,引用istringstream的确是一种比较快捷的方法。
解决这个问题的主要思想:
pattern:abba,我们编码为0110;对于pattern中的每个字符,我们将其映射到其第一次出现的位置,这个可以直接利用string的find_first_of得到。
str = “dog cat cat fish”,我们编码为0113;对于vector来说,如何实现将每个单词映射到其第一次出现的位置,我引用了map。
class Solution { public: bool wordPattern(string pattern, string str) { int* patternCode=new int[pattern.size()];//对pattern进行编码 for(unsigned int i=0;i<pattern.size();i++) patternCode[i]=pattern.find_first_of(pattern[i]); vector<string> vec; map<string,int> strMap; istringstream ss(str); string word; while(ss>>word) vec.push_back(word);//分割str为单词,存储在vector中 int* strCode=new int[vec.size()]; for(unsigned int i=0;i<vec.size();i++)//为str进行编码 { if(!strMap.count(vec[i])) { strMap[vec[i]]=i; strCode[i]=i; } else strCode[i]=strMap[vec[i]]; } if(pattern.size()!=vec.size())//两者编码长度不同,返回错误 return false; for(unsigned int i=0;i<vec.size();i++) if(patternCode[i]!=strCode[i]) return false; return true; } };
相关文章推荐
- 模拟结婚和离婚
- JVM——Java虚拟机架构
- JVM——Java虚拟机架构
- Zen Coding的一种快速编写HTML/CSS代码的方法
- 策略模式与开发实践
- 交换两个变量值的五种方法及相关解析
- Windows中进程的内存结构
- 75. Sort Colors
- HiveQL语法
- 流计算概述(一)
- Android中常见的布局文件的属性
- iOS文件管理(一)
- JVM--堆栈具体内存分配
- C# 知识汇总(一)
- FMS/AMS5安装后的简单应用和配置注意事项
- php:undefined index的几种解决方法
- hdoj-5645-DZY Loves Balls
- 实现文件上传服务器某一路径或者删除服务器某一路径下的文件
- 资源加载和activity生命周期管理
- DEDECMS之二 如何修改模板页