Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-06-12 #266

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-06-12

SaraadKun commented 2 years ago

890. 查找和替换模式

class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> ans = new ArrayList<>();
        int n = pattern.length();
        char[] p = pattern.toCharArray();
        out: for (int i = 0; i < words.length; i++) {
            char[] d1 = new char[26];
            char[] d2 = new char[26];
            char[] word = words[i].toCharArray();
            for (int j = 0; j < n; j++) {
                //dict[word[j] - 'a'] == p[j]
                if ((d1[word[j] - 'a'] < 'a' && d2[p[j] - 'a'] < 'a') 
                    || (d1[word[j] - 'a'] == p[j] && d2[p[j] - 'a'] == word[j]) ){
                    d1[word[j] - 'a'] = p[j];
                    d2[p[j] - 'a'] = word[j];
                } else {
                    continue out;
                } 
            }
            ans.add(words[i]);
        }
        return ans;
    }
}

WeChat: Saraad

dreamhunter2333 commented 2 years ago
package main

import "fmt"

/*
 * @lc app=leetcode.cn id=890 lang=golang
 *
 * [890] 查找和替换模式
 */

// @lc code=start
func findAndReplacePattern(words []string, pattern string) []string {
    res := make([]string, 0)
    for _, word := range words {
        if !check(word, pattern) {
            continue
        }
        res = append(res, word)
    }
    return res
}

func check(word string, pattern string) bool {
    cache := make(map[byte]byte)
    cache2 := make(map[byte]byte)
    for i, _ := range pattern {
        if value, ok := cache[pattern[i]]; ok && value != word[i] {
            return false
        }
        if value, ok := cache2[word[i]]; ok && value != pattern[i] {
            return false
        }
        cache[pattern[i]] = word[i]
        cache2[word[i]] = pattern[i]
    }
    return true
}

// @lc code=end
func main() {
    fmt.Println(findAndReplacePattern([]string{"abc", "deq", "mee", "aqq", "dkd", "ccc"}, "abb"))
}

微信id: 而我撑伞 来自 vscode 插件