题目

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. NET Core应用中如何记录和查看日志

    NET Core应用中如何记录和查看日志 日志记录不仅对于我们开发的应用,还是对于ASP.NET Core框架功能都是一项非常重要的功能特性.我们知道ASP.NET Core使用的是一个极具扩展性的日 ...

  2. C - AtCoDeerくんと選挙速報 / AtCoDeer and Election Report

    ceil有毒啊..用ceil一直错. 思路就是模拟吧,设当前的答案是ansx和ansy. 如果比例是小于ansx的,那么就要乘以一个倍数k1,使得a * k1 >= ansx的. 所以就用cei ...

  3. Unbuntu 自动重启MySQL

    上个月,通过Unbuntu搭建了WordPress,一切运行良好. UBUNTU搭建WORDPRESS-MYSQL-APACHE 但是,最近几天,不知道啥情况,MySQL偶尔会出现Stop:影响了bl ...

  4. SQL server 游标,随机数使用

    SELECT * FROM [goods] DECLARE test_cursor CURSOR scroll FOR SELECT goods_no, [unitprice] FROM [goods ...

  5. 将JWT与Spring Security OAuth结合使用

    1.概述 在本教程中,我们将讨论如何使用Spring Security OAuth2实现来使用JSON Web令牌. 我们还将继续构建此OAuth系列的上一篇文章. 2. Maven配置 首先,我们需 ...

  6. IQueryable和IEnumerable的区别

  7. springboot集成shiro实现验证码校验

    github:https://github.com/peterowang/shiro/ 这里实现验证码校验的思路是自己添加一个Filter继承FormAuthenticationFilter,Form ...

  8. 使用jdbc完成curd操作

    jdbc: java操作数据库,jdbc是oracle公司指定的一套规范(一套接口) 驱动:jdbc的实现类,由数据库厂商提供 我们可以通过一套规范操作不同的数据库(多态) jdbc作用: 连接数据库 ...

  9. pc端常见布局样式总结(针对常见的)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  10. 2017.10.3 QBXT 模拟赛

    题目链接 T1 模拟 #include <cstring> #include <cstdio> #define N 105000 int L,R; char s[N]; int ...