博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】290. Word Pattern 解题小结
阅读量:4594 次
发布时间:2019-06-09

本文共 1472 字,大约阅读时间需要 4 分钟。

题目:

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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

采取的办法是建立两个map,相互映射。为什么用一个map不够?如果面对第4个例子,abba,dog dog dog dog,a和b都会映射到dog,因为你要保证1对1映射,那么可以采取反面映射过来。

class Solution {public:    bool wordPattern(string pattern, string str) {        unordered_map
dictP; unordered_map
dictS; string buff; int idx = 0; for (int i = 0; i < pattern.size(); i++){ buff.clear(); while (idx < str.size() && str[idx] != ' '){ buff.push_back(str[idx++]); } if (buff.empty()) return false; idx++; if (dictP.find(pattern[i]) == dictP.end() && dictS.find(buff) == dictS.end()){ dictP[pattern[i]] = buff; dictS[buff] = pattern[i]; } else if (dictP[pattern[i]] != buff || dictS[buff] != pattern[i]) return false; } if (idx == 0 || idx < str.size()) return false; return true; }};

 

转载于:https://www.cnblogs.com/Doctengineer/p/5824834.html

你可能感兴趣的文章
集合相关概念
查看>>
Memcache 统计分析!
查看>>
(Python第四天)字符串
查看>>
个人介绍
查看>>
使用python动态特性时,让pycharm自动补全
查看>>
关于R软件的安装
查看>>
MySQL数据库免安装版配置
查看>>
你必知必会的SQL面试题
查看>>
html5 Canvas绘制时钟以及绘制运动的圆
查看>>
Unity3D热更新之LuaFramework篇[05]--Lua脚本调用c#以及如何在Lua中使用Dotween
查看>>
JavaScript空判断
查看>>
洛谷 P1439 【模板】最长公共子序列(DP,LIS?)
查看>>
python timeit
查看>>
Wireless Network 并查集
查看>>
51nod 1019 逆序数
查看>>
Java_Set用法总结
查看>>
Codeforces Round #160 (Div. 2) D. Maxim and Restaurant(DP)
查看>>
Exchange Port
查看>>
oracle 01578
查看>>
在source中查看代码
查看>>