[Leetcode][Medium] 890. Find and Replace Pattern

Problem

You have a list of words and a pattern, and you want to know which words in words matches the pattern.

Example

Input: words = [“abc”,“deq”,“mee”,“aqq”,“dkd”,“ccc”], pattern = “abb”
Output: [“mee”,“aqq”]
Explanation: “mee” matches the pattern because there is a permutation {a -> m, b -> e, …}.
“ccc” does not match the pattern because {a -> c, b -> c, …} is not a permutation,
since a and b map to the same letter.

Answer
class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> res;
        string nP = normalize(pattern);
        
        for (auto& word: words) {
            if (normalize(word) == nP) res.push_back(word);
        }
        return res;
    }
    
    string normalize(string& s) {
        unordered_map<char,int> map;
        for (auto& c : s) if (!map.count(c)) map[c] = map.size();
        
        string nS;
        for (auto& c : s) nS += map[c];
        return nS;
    }
};
Explanation

比较两个字符串是否具有相同的pattern.

  1. 我们可以对两个字符串分别进行normalize
    normalize的根据就是遍历每个字符,通过unordered_map来记录该字符是字符串中出现的顺序位置.
    根据字符串的出现顺序,我们可以把原字符串转化为normalize后的字符串.
  2. 比较两个字符串的normalize后是否相同就可以判断是否有相同的patter
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值