LeetCode Word Pattern
来源:互联网 发布:淘宝商品找不到了 编辑:程序博客网 时间:2024/06/16 06:29
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进行单词split存放到vector中,然后利用两个map结构,分别检查char与string是否一一对应
class Solution {public: bool wordPattern(string pattern, string str) { //解题思路:首先对str采用split分出所有单词,然后将pattern中的每个字母与单词绑定,如果存在不匹配的false int index = 0; int start = 0; int n = str.length(); vector<string> words; while(str[index] != '\0') { if(str[index] != ' ') ++index; else { words.push_back(str.substr(start,index-start)); start = index+1; ++index; } } words.push_back(str.substr(start,n-start)); if(words.size() != pattern.size()) return false; map<char,string> sta; map<string,char> sta1; for(int i = 0;i<pattern.size();i++) { //cout<<words[i]<<endl; if(sta.count(pattern[i]) == 0) sta[pattern[i]] = words[i]; else { string s = sta[pattern[i]]; if(s != words[i]) return false; } if(sta1.count(words[i]) == 0) sta1[words[i]] = pattern[i]; else { char c = sta1[words[i]]; if(c != pattern[i]) return false; } } return true; }};
0 0
- leetcode | Word Pattern
- 【leetcode】290. Word Pattern
- leetcode 290: Word Pattern
- [Leetcode]Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- 【leetcode】290. Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- LeetCode 2 Word Pattern
- leetcode word-pattern
- leetcode: Word Pattern
- leetcode:Word Pattern
- [Leetcode]Word Pattern
- LeetCode Word Pattern
- LeetCode-Word Pattern
- LeetCode:Word Pattern
- leetcode之Word Pattern
- LeetCode 29. Divide Two Integers
- 自动播放的ViewFlipper
- 随机生成10个数求和方法(11)
- leetcode : 312. Burst Balloons : dp矩阵加括号
- 正则表达式-替换网址
- LeetCode Word Pattern
- SQL2005四个排名函数(row_number、rank、dense_rank和ntile)的比较
- Python叠加两幅栅格图像
- java多线程的好处.1
- 41.leetcode题目217. Contains Duplicate(哈希方法还没做)
- 基于的epoll模型的简单http服务器
- 06 VoLTE - Signaling - Call Release and Error Handling
- BSoj : 4608【CQOI2016】路由表
- 关于java以及引申到其他技术的学习方法的小结