题目

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代码

  1. class Solution {
  2. public:
  3. bool wordPattern(string pattern, string str) {
  4. if (str.empty())
  5. return false;
  6. //从输入的字符串源串得到字符串数组
  7. vector<string> strs;
  8. string s = "";
  9. for (int i = 0; str[i] != '\0'; ++i)
  10. {
  11. if (str[i] == ' ')
  12. {
  13. strs.push_back(s);
  14. s = "";
  15. }
  16. else
  17. s += str[i];
  18. }//for
  19. //保存末尾单词
  20. strs.push_back(s);
  21. if (pattern.size() != strs.size())
  22. return false;
  23. //判断模式匹配
  24. int len = pattern.size();
  25. unordered_map<char, string> um1;
  26. unordered_map<string, char> um2;
  27. for (int i = 0; i < len; ++i)
  28. {
  29. auto iter1 = um1.find(pattern[i]);
  30. auto iter2 = um2.find(strs[i]);
  31. if (iter1 != um1.end() && iter2 != um2.end())
  32. {
  33. if ((*iter1).second == strs[i] && (*iter2).second == pattern[i])
  34. continue;
  35. else
  36. return false;
  37. }//if
  38. else if (iter1 == um1.end() && iter2 != um2.end())
  39. return false;
  40. else if (iter1 != um1.end() && iter2 == um2.end())
  41. return false;
  42. else
  43. um1.insert({ pattern[i], strs[i] });
  44. um2.insert({ strs[i], pattern[i] });
  45. }//for
  46. return true;
  47. }
  48. };

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. CentOS 6.4 中yum命令安装php5.2.17

    最近给公司部署服务器的时候发现他们提供的服务器是centos6.4系统的,装好系统和相关服务httpd,mysql,php,一跑代码,发现php5.3中的zend加密不能用,安装Zend Guard ...

  2. java wait(),notify(),notifyAll()

    wait()的作用是使当前执行代码的线程进行等待,此方法是Object类的方法,该方法用来将当前线程置入“预执行队列”中,并且在wait()所带的代码处停止执行,直到接到通知或被中断位置.在调用wai ...

  3. @Autowired的使用--Spring规范解释,推荐对构造函数进行注释

    一 在编写代码的时候,使用@Autowired注解是,发现IDE报的一个警告,如下: Spring Team recommends "Always use constructor based ...

  4. IO(File、递归)

      第1章 File 1.1 IO概述 回想之前写过的程序,数据都是在内存中,一旦程序运行结束,这些数据都没有了,等下次再想使用这些数据,可是已经没有了.那怎么办呢?能不能把运算完的数据都保存下来,下 ...

  5. POJ3252Round Numbers(数位dp)

    题意 给出区间$[A, B]$,求出区间内的数转成二进制后$0$比$1$多的数的个数 $1 \leqslant A, B \leqslant 2,000,000,000$ Sol 比较zz的数位dp ...

  6. Myeclipse连接数据库删除数据库(JDBC)

    package com.test.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Pr ...

  7. H5的storage(sessionstorage&localStorage)简单存储删除

    众所周知,H5的storage有sessionstorage&localStorage,其中他们的共同特点是API相同 下面直接上代码,storage中的存储与删除: <!DOCTYPE ...

  8. ABAP扫雷游戏

    . INCLUDE <icon>. CONSTANTS: " >> board cell values blank_hidden ', blank_marked TY ...

  9. javascript组件封装中一段通用代码解读

    有图有真相,先上图. 相信很多想去研究源码的小伙伴一定被这段代码给吓着了把,直接就打消了往下看下去的想法.我刚开始看的时候也是有点一头雾水,这是什么东东这么长,但是慢慢分析你就会发现其中的奥秘,且听我 ...

  10. BaseAdapter.notifyDataSetChanged()之观察者设计模式及源码分析

    BaseAdapter.notifyDataSetChanged()的实现涉及到设计模式-观察者模式,详情请参考我之前的博文设计模式之观察者模式 Ok,回到notifyDataSetChanged进行 ...