题目

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.

分析

字符串的模式匹配,类似于离散数学中的双向映射问题。

利用unordered_map数据结构建立双向映射,逐个判断匹配。

AC代码

class Solution {
public:
bool wordPattern(string pattern, string str) {
if (str.empty())
return false; //从输入的字符串源串得到字符串数组
vector<string> strs;
string s = "";
for (int i = 0; str[i] != '\0'; ++i)
{
if (str[i] == ' ')
{
strs.push_back(s);
s = "";
}
else
s += str[i];
}//for
//保存末尾单词
strs.push_back(s); if (pattern.size() != strs.size())
return false;
//判断模式匹配
int len = pattern.size();
unordered_map<char, string> um1;
unordered_map<string, char> um2;
for (int i = 0; i < len; ++i)
{
auto iter1 = um1.find(pattern[i]);
auto iter2 = um2.find(strs[i]); if (iter1 != um1.end() && iter2 != um2.end())
{
if ((*iter1).second == strs[i] && (*iter2).second == pattern[i])
continue;
else
return false;
}//if
else if (iter1 == um1.end() && iter2 != um2.end())
return false;
else if (iter1 != um1.end() && iter2 == um2.end())
return false;
else
um1.insert({ pattern[i], strs[i] });
um2.insert({ strs[i], pattern[i] });
}//for
return true;
}
};

GitHub测试程序源码

LeetCode(290) Word Pattern的更多相关文章

  1. LeetCode(79) Word Search

    题目 Given a 2D board and a word, find if the word exists in the grid. The word can be constructed fro ...

  2. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  3. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  4. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  5. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  6. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  7. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  8. LeetCode(107) Binary Tree Level Order Traversal II

    题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...

  9. LeetCode(4)Median of Two Sorted Arrays

    题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...

随机推荐

  1. 转 v$session_longops视图

    转http://www.dbdream.com.cn/2013/10/14/vsession_longops%E8%A7%86%E5%9B%BE/ 1.有的时候不准确 ,我看到 session wai ...

  2. 手动添加日期到mysql数据库

    //获得jsp页面上的数据 String dates=request.getParameter("dates"); //使用预定格式将日期转换为字符串 SimpleDateForm ...

  3. App配置页面头部

    记录一下 App配置页面头部 例 上图红色框部分就是自己配置的头部 //我的客户 "/OACustomer/Index": { title: "我的客户", h ...

  4. spring Cloud中,解决Feign/Ribbon整合Hystrix第一次请求失败的问题?

    Spring Cloud中,Feign和Ribbon在整合了Hystrix后,可能会出现首次调用失败的问题,要如何解决该问题呢? 造成该问题的原因 Hystrix默认的超时时间是1秒,如果超过这个时间 ...

  5. python 之format字符串格式化

    print函数之format字符串格式化方法的使用与学习笔记. 一.映射关系 (1)“映射”示例,以下通过位置举例说明: [+]Example_1: >>> print(" ...

  6. 【转载】UWP应用设置和文件设置:科普

    数据有两个基本的分类,应用数据和用户数据,而用户数据则为由用户拥有的数据,如文档,音乐或电子邮件等,下面将大致的介绍一下应用数据的基本操作. 应用数据:应用数据包含APP的状态信息(如运行时状态,用户 ...

  7. 使用工具Source Monitor测量您Java代码的环复杂度

    代码的环复杂度(Cyclomatic complexity,有时也翻译成圈复杂度)是一种代码复杂度的衡量标准,在1976年由Thomas J. McCabe, Sr. 提出. 来看看计算公式. 代码环 ...

  8. 重温Javascript(二)-对象

    对象 可以想象成散列表,键值对,值可以是数据或函数 创建对象的方式 1.工厂模式 function createPerson(name, age, job){ var o = new Object() ...

  9. CodeForces 77C Beavermuncher-0xFF (树形dp)

    不错的树形dp.一个结点能走多次,树形的最大特点是到达后继的路径是唯一的,那个如果一个结点无法往子结点走,那么子结点就不用考虑了. 有的结点不能走完它的子结点,而有的可能走完他的子节点以后还会剩下一些 ...

  10. ArcGis server发布地图服务

    ArcGIS server发布服务: 首先修改地图文档属性中的关联默认数据库 最后使用分享将地图服务发布到server上,是地图服务可以使用: 注意一定要勾选 Feature Access选项 fea ...