资讯专栏INFORMATION COLUMN

Find and Replace Pattern

ityouknow / 754人阅读

1. 题目

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.
例子

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.
2. 我的解法
var findAndReplacePattern = function(words, pattern) {
    const norPatter = toNormal(pattern)
    return words.filter( v => toNormal(v) === norPatter)
};

var toNormal = function(string) {
    let li = string.split("")
    let tem = []
    let tem2 = []
    let i = 0
    li.forEach(v => {
       let index = tem2.indexOf(v)
       if(index===-1) {
           i++
            tem.push(i)  
       } else {
           tem.push(tem[index])
       }
        tem2.push(v)
    })
    return tem.join("")
}
Runtime: 60 ms, faster than 99.18% of JavaScript online submissions for Find and Replace Pattern.
Memory Usage: 35.1 MB, less than 54.17% of JavaScript online submissions for Find and Replace Pattern.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/103941.html

相关文章

  • 在Python中查找和替换文本

    摘要:最简单的查找替换在中查找和替换非常简单,如果当前对象是一个字符串时,你可以使用该类型提供的或者方法查找指定的字符,如果能找到则会返回字符第一次出现的索引,如果不存在则返回。下面是正则查找的简单示例。 最简单的查找替换 在Python中查找和替换非常简单,如果当前对象是一个字符串str时,你可以使用该类型提供的find()或者index()方法查找指定的字符,如果能找到则会返回字符第一次...

    B0B0 评论0 收藏0
  • Leetcode 44 Wildcard Matching 通配符匹配

    摘要:难度题目给出一个字符串和一个要求我们给出这个字符串是否匹配这个其中通配符跟我们平常见到的一样是和代表任意单个字符代表一个或多个字符这个题跟简单正则匹配比较类似可以跟这里面第二个解法一样采取类似的动态规划解法在里取中间某个确定的字符串序列将字 Implement wildcard pattern matching with support for ? and *. ? Matches ...

    SimonMa 评论0 收藏0
  • 搞定PHP面试 - 正则表达式知识点整理

    摘要:是决定正则表达式匹配规则的主要部分。二分隔符分隔符的选择当使用函数的时候,正则表达式必须由分隔符闭合包裹。果分隔符经常在正则表达式内出现,最好使用其他分隔符来提高可读性。需要将一个字符串放入正则表达式中使用时,可以用函数对其进行转义。 一、简介 1. 什么是正则表达式 正则表达式(Regular Expression)就是用某种模式去匹配一类字符串的一种公式。正则表达式使用单个字符串来...

    AaronYuan 评论0 收藏0

发表评论

0条评论

ityouknow

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<