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

方法1: double hash

思路:

用了一刷和205. Isomorphic Strings一样naive的双哈希表。205题当中还有一种比较巧妙的做法,通过vector来建立函数检查一一映射,这里由于单词没有明显对应的vector index,相当于需要hash一遍,和double hash的做法就差不多了。分四种情况讨论?反而更麻烦。

易错点

  1. 双向映射要保证一一对应
  2. 最后还要检查i == n是因为有可能pattern和str长度不一样,如果str先结束,此时i = n返回false,也就是i == n在防守的情况。但是如果pattern先结束,循环并不会停下来,由于pattern是string,pattern[i]也不会像vector一样出现heap-overflow,而是直接调取该内存位置的值建立映射,大概率会返回false。但是太随意了,还是检查一下size是否相等。

Input
“jquery”
“jquery”
Output
true
Expected
false

Complexity

Time complexity: O(n)
Space complexity: O(n)

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> hash;
        unordered_map<string, char> hash_r;
        istringstream in(str);
        
        int i = 0, n = pattern.size();
        for (string word; in >> word; i++){
            if (hash.count(pattern[i]) == 0 && hash_r.count(word) == 0){
                hash_r[word] = pattern[i];
                hash[pattern[i]] = word;
            }
            else if (hash[pattern[i]] != word || hash_r[word] != pattern[i]){
                return false;
            }
        }
        
        return i == n;
    }
};

方法2: one hash

思路:

每次不但遍历一遍hash看char是否存在,还要遍历一次hash中所有word看是否已经被映射到某个char。

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> hash;
        istringstream in(str);
        
        int i = 0, n = pattern.size();
        for (string word; in >> word; i++){
            if (hash.count(pattern[i]) == 0){
                for (auto a: hash){
                    if (word == a.second){
                        return false;
                    }
                }
                hash[pattern[i]] = word;
            }
            else if (hash[pattern[i]] != word){
                return false;
            }
        }
        
        return i == n;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值