LeetCode: 890. Find and Replace Pattern

LeetCode: 890. Find and Replace Pattern

题目描述

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

A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.

Example 1:

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.

Note:

1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20

解题思路

对每个字符根据其出现顺序进行编号,然后将字符串用编号表示。如果编号表示的字符串和模式串相吻合,则符合模式。

AC 代码

class Solution {
    // 根据字符出现的顺序对字符编号,并将原字符串用编号表示
    vector<int> getPatternVec(string pattern)
    {
        string chars;
        vector<int> ans;
        for(char x : pattern)
        {
            if(chars.find_first_of(x) == chars.npos)
            {
                chars.push_back(x);
            }
        }

        for(char x : pattern)
        {
            ans.push_back(chars.find_first_of(x));
        }

        return ans;
    }
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> ans;
        vector<int> patternVec = getPatternVec(pattern);
        for(size_t i = 0; i < words.size(); ++i)
        {
            if(getPatternVec(words[i]) == patternVec)
            {
                ans.push_back(words[i]);
            }
        }

        return ans;
    }
};
全部评论

相关推荐

勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
正在热议
# 25届秋招总结 #
442570次浏览 4512人参与
# 春招别灰心,我们一人来一句鼓励 #
41986次浏览 533人参与
# 阿里云管培生offer #
120263次浏览 2220人参与
# 地方国企笔面经互助 #
7962次浏览 18人参与
# 同bg的你秋招战况如何? #
76743次浏览 563人参与
# 实习必须要去大厂吗? #
55775次浏览 961人参与
# 北方华创开奖 #
107436次浏览 599人参与
# 虾皮求职进展汇总 #
115687次浏览 886人参与
# 如果你有一天可以担任公司的CEO,你会做哪三件事? #
11584次浏览 287人参与
# 实习,投递多份简历没人回复怎么办 #
2454714次浏览 34857人参与
# 提前批简历挂麻了怎么办 #
149906次浏览 1977人参与
# 在找工作求抱抱 #
906025次浏览 9421人参与
# 如果公司给你放一天假,你会怎么度过? #
4757次浏览 55人参与
# 你投递的公司有几家约面了? #
33206次浏览 188人参与
# 投递实习岗位前的准备 #
1195950次浏览 18549人参与
# 机械人春招想让哪家公司来捞你? #
157635次浏览 2267人参与
# 双非本科求职如何逆袭 #
662248次浏览 7397人参与
# 发工资后,你做的第一件事是什么 #
12734次浏览 62人参与
# 工作中,努力重要还是选择重要? #
35815次浏览 384人参与
# 简历中的项目经历要怎么写? #
86920次浏览 1516人参与
# 参加完秋招的机械人,还参加春招吗? #
20133次浏览 240人参与
# 我的上岸简历长这样 #
452024次浏览 8088人参与
牛客网
牛客企业服务