leetcode_Word Pattern
来源:互联网 发布:手机vpn 知乎 编辑:程序博客网 时间:2024/06/08 20:12
以下为问题描述:
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.
题目的意思是要我们判断pattern和str是否匹配,匹配的条件是pattern中的字母与str中的单词是否能一一对应,以pattern = “abba”, str = “dog cat cat dog”为例,a与dog对应,b与cat对应。
解题思路:建立pattern哈希表,每当截取一个子串,就将其与哈希表内的字符串比较。
代码
class Solution {public: bool wordPattern(string pattern, string str) { vector<string> hashTable(26,""); //pattern哈希,例如a->0->dog,b->1->cat int indexOfParttern = 0; //pattern下标 int start = 0; //用于截取子串,子串的起始下标 int end = 0; //用于截取子串,子串的结束下标+1 int count = 0; string sub = str; while((end = sub.find_first_of(' '))!=-1) { sub = sub.substr(0, end); int hashPos = pattern[indexOfParttern++]-'a'; if (hashTable[hashPos].empty()) { //如果即将插入哈希表的值在哈希表已经存在则返回false for (int i = 0; i != hashTable.size(); ++i) { if (hashTable[i] == sub) { return false; } } hashTable[hashPos] = sub; } else { if (hashTable[hashPos]!= sub) { return false; } } start += end+1; sub = str.substr(start, str.length()-start); ++count; } //若模式串字母个数与str的子串个数不同则false if (pattern.length() != indexOfParttern + 1) { return false; } //判断最后一个子串 int hashPos = pattern[indexOfParttern++]-'a'; if (hashTable[hashPos].empty()) { for (int i = 0; i != hashTable.size(); ++i) { if (hashTable[i] == sub) { return false; } } hashTable[hashPos] = sub; } else { if (hashTable[hashPos]!= sub) { return false; } } return true; }};
- leetcode_Word Pattern
- leetcode_Word Pattern
- LeetCode_Word Ladder
- LeetCode_Word Break
- LeetCode_Word Ladder
- LeetCode_Word Search
- leetcode_Word Break
- leetcode_Word Search
- leetCode_Word Break
- leetCode_Word BreakII
- Leetcode_word-search(c++ version)
- Leetcode_word-break-ii
- Leetcode_word-ladder(c++ version)
- Leetcode_word-ladder-ii
- LeetCode_Word Break II
- 【题解】leetcode_Word Frequency
- leetCode_Word Ladder【BFS】
- Leetcode_word-break(c++ and python version)
- Android 中String文件通配符使用
- 后面一点计划吧
- Django官方【实例】-简单的全方位例子
- F8App-ReactNative项目源码分析2-服务器端
- 第11周补充(4)时间类
- leetcode_Word Pattern
- 新浪微博用户兴趣建模系统架构
- Android事件分发机制完全解析(上)
- ios 开发学习日志 自定义alertView 3
- Linux下QT5.6打开位置
- Android wpa_supplicant源码分析--运行方式
- NYOJ 88-汉诺塔(一)【罗汉塔定理f(x)=2*f(x-1)+1,快速幂模板】
- iOS开发系列--UITableView全面解析
- 关于java.util.Vector 或 java.util.Hashtable类过时的讨论