leetcode 290. Word Pattern

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.

Example 1:

Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:

Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:

Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:

Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题目大意:给定两个字符串pattern和str,pattern字符串表示模式,判断str字符串的模式是否和pattern一致,若一致返回true,不一致返回false。

代码:
class Solution {
public:
bool wordPattern(string pattern, string str){
  unordered_map<string, char> hashmap;
  unordered_map<char, string> phashmap;
  int i = 0, j = 0, lens = str.size(), lenp = pattern.size();
  while(i < lenp && j < lens){
    int pos = str.find(' ', j);
    string sub = str.substr(j, pos-j);
    if(phashmap.count(pattern[i]) && phashmap[pattern[i]] != sub)
      return false;
    if(hashmap.count(sub) && hashmap[sub] != pattern[i] )
      return false;
      hashmap[sub] = pattern[i];
    phashmap[pattern[i]] = sub;
    ++i;
    j = pos+1;
//
  }
  return i == lenp && j == lens;
}
};

一个反思:开始看到这个题觉得是个水题,知道要把str和pattern对应起来,但是代码死活写不出来,尝试了自己写了个split把str按照空格每个词都分出来,然后for循环又写不好了,最后网上看了别人的思路才发现是自己最基本的数据结构没有掌握好,unorderedmap的许多用法都很模糊,对哈希表理解也不深刻,水题才是检验基础的标尺啊,很惭愧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值