leetcode 290: Word Pattern
2016-02-24 01:03
246 查看
问题描述:
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.
思路:
首先把str给分割成单词数组,然后用笨方法,保存双向映射,这就是为什么代码中设置两个map。遍历数组,用map来查找和插入映射。代码:
class Solution { public: bool wordPattern(string pattern, string str) { //split into word list vector<string> wordlist; string::size_type pos; str += " "; int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(" ", i); //find the space position if (pos < size) { string word = str.substr(i, pos - i); //extract the word if (word != "") //record the word { wordlist.push_back(word); } i = pos; } } int w_size = wordlist.size(); int p_size = pattern.size(); if (w_size != p_size) return false; map<char, string> c2s_mapped; //map char to string map<string, char> s2c_mapped; //map string to char for (int i = 0; i < p_size; i++) { char c_now = pattern[i]; string s_now = wordlist[i]; map<char, string>::iterator it_c2s = c2s_mapped.find(c_now); if (it_c2s != c2s_mapped.end()) //found { if (it_c2s->second != s_now) return false; } else //not found { map<string, char>::iterator it_s2c = s2c_mapped.find(s_now); if (it_s2c != s2c_mapped.end()) return false; c2s_mapped.insert(pair<char, string>(c_now, s_now)); s2c_mapped.insert(pair<string, char>(s_now, c_now)); } } return true; } };
相关文章推荐
- 【Android】沉浸式状态栏的两种实现方式
- 博客园自定义标题、阅读目录、导航栏、活动的推荐&反对按钮
- ECMAScript 6规范总结(长文慎入)
- Android屏幕适配
- matlab 信号平滑处理方法
- 个人进阶之路——自定义控件(2)
- kidd风的IOS日志之UIApplication详解
- 【数据结构与算法分析 】第三章总结
- exchange 2010 初始化失败一例
- 【Java基础学习】DecimalFormat用法
- 【数据结构与算法分析】第一章、第二章总结
- (java)Container With Most Water
- struts2标签与jstl标签的混合使用
- 修复gnome3下chrome鼠标主题不正确的问题
- android 成长日记 6.ListView详解
- JSunpack-n模拟WireShark拦截文件传输
- JSunpack-n模拟WireShark拦截文件传输
- 异常01
- ubuntu12.04安装tftp服务
- 【数据结构与算法分析】第一章学习总结