返回介绍

solution / 0800-0899 / 0890.Find and Replace Pattern / README_EN

发布于 2024-06-17 01:03:33 字数 5562 浏览 0 评论 0 收藏 0

890. Find and Replace Pattern

中文文档

Description

Given a list of strings words and a string pattern, return _a list of_ words[i] _that match_ pattern. You may return the answer in any order.

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.

 

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.

Example 2:

Input: words = ["a","b","c"], pattern = "a"
Output: ["a","b","c"]

 

Constraints:

  • 1 <= pattern.length <= 20
  • 1 <= words.length <= 50
  • words[i].length == pattern.length
  • pattern and words[i] are lowercase English letters.

Solutions

Solution 1

class Solution:
  def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
    def match(s, t):
      m1, m2 = [0] * 128, [0] * 128
      for i, (a, b) in enumerate(zip(s, t), 1):
        if m1[ord(a)] != m2[ord(b)]:
          return False
        m1[ord(a)] = m2[ord(b)] = i
      return True

    return [word for word in words if match(word, pattern)]
class Solution {
  public List<String> findAndReplacePattern(String[] words, String pattern) {
    List<String> ans = new ArrayList<>();
    for (String word : words) {
      if (match(word, pattern)) {
        ans.add(word);
      }
    }
    return ans;
  }

  private boolean match(String s, String t) {
    int[] m1 = new int[128];
    int[] m2 = new int[128];
    for (int i = 0; i < s.length(); ++i) {
      char c1 = s.charAt(i);
      char c2 = t.charAt(i);
      if (m1[c1] != m2[c2]) {
        return false;
      }
      m1[c1] = i + 1;
      m2[c2] = i + 1;
    }
    return true;
  }
}
class Solution {
public:
  vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
    vector<string> ans;
    auto match = [](string& s, string& t) {
      int m1[128] = {0};
      int m2[128] = {0};
      for (int i = 0; i < s.size(); ++i) {
        if (m1[s[i]] != m2[t[i]]) return 0;
        m1[s[i]] = i + 1;
        m2[t[i]] = i + 1;
      }
      return 1;
    };
    for (auto& word : words)
      if (match(word, pattern)) ans.emplace_back(word);
    return ans;
  }
};
func findAndReplacePattern(words []string, pattern string) []string {
  match := func(s, t string) bool {
    m1, m2 := make([]int, 128), make([]int, 128)
    for i := 0; i < len(s); i++ {
      if m1[s[i]] != m2[t[i]] {
        return false
      }
      m1[s[i]] = i + 1
      m2[t[i]] = i + 1
    }
    return true
  }
  var ans []string
  for _, word := range words {
    if match(word, pattern) {
      ans = append(ans, word)
    }
  }
  return ans
}
function findAndReplacePattern(words: string[], pattern: string): string[] {
  return words.filter(word => {
    const map1 = new Map<string, number>();
    const map2 = new Map<string, number>();
    for (let i = 0; i < word.length; i++) {
      if (map1.get(word[i]) !== map2.get(pattern[i])) {
        return false;
      }
      map1.set(word[i], i);
      map2.set(pattern[i], i);
    }
    return true;
  });
}
use std::collections::HashMap;
impl Solution {
  pub fn find_and_replace_pattern(words: Vec<String>, pattern: String) -> Vec<String> {
    let pattern = pattern.as_bytes();
    let n = pattern.len();
    words
      .into_iter()
      .filter(|word| {
        let word = word.as_bytes();
        let mut map1 = HashMap::new();
        let mut map2 = HashMap::new();
        for i in 0..n {
          if map1.get(&word[i]).unwrap_or(&n) != map2.get(&pattern[i]).unwrap_or(&n) {
            return false;
          }
          map1.insert(word[i], i);
          map2.insert(pattern[i], i);
        }
        true
      })
      .collect()
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文