美文网首页
查找和替换模式

查找和替换模式

作者: WAI_f | 来源:发表于2020-07-18 21:42 被阅读0次

题目:

你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words 中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。

示例:

输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
输出:["mee","aqq"]
解释:
"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
因为 a 和 b 映射到同一个字母。

解题方法:

这道题有点像正则化匹配,就是找words里面符合pattern特点的字符串。但是怎么判断说实话我自己做还是挺蒙的,这里搬运一下题解中的优秀方法:

利用string的find函数判断两个字符串相同位置的字母是否在字符串中出现的状态(位置)相同。

代码和结果:

class Solution {
public:
    bool compare(string word,string pattern)
    {
        if(word.size()!=pattern.size()) return false;
        else
        {
            for(int i=0;i<word.size();i++)
            {
                if(word.find(word[i])!=pattern.find(pattern[i]))
                    return false;
            }
            return true;
        }
    }
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> res;
        for(int i=0;i<words.size();i++)
        {
            if(compare(words[i],pattern))
                res.push_back(words[i]);
        }
        return res;
    }
};
运行结果:

最近逐渐忙起来了,刷题的难题也上来了,总的来说就是有点累。

原题链接:https://leetcode-cn.com/problems/find-and-replace-pattern/

相关文章

网友评论

      本文标题:查找和替换模式

      本文链接:https://www.haomeiwen.com/subject/hazfkktx.html