当前位置:网站首页>LeetCode 890(C#)

LeetCode 890(C#)

2022-07-07 19:05:00 Just be interesting

List of articles

subject

You have a list of words words And a pattern pattern, Do you want to know words Which words in match the pattern .

If there is an arrangement of letters p , Make every letter in the pattern x Replace with p(x) after , We get the words we need , So the words match the patterns .

( Think about it , The arrangement of letters is from letter to letter : Each letter maps to another letter , No two letters map to the same letter .)

return words List of words matching the given pattern in .

You can return the answers in any order .

Example :

Input :words = [“abc”,“deq”,“mee”,“aqq”,“dkd”,“ccc”], pattern = “abb”
Output :[“mee”,“aqq”]

explain :
“mee” Match pattern , Because there are permutations {a -> m, b -> e, …}.
“ccc” Does not match pattern , because {a -> c, b -> c, …} It's not a permutation .
because a and b Map to the same letter .

Code

public class Solution 
{
    
    public IList<string> FindAndReplacePattern(string[] words, string pattern) 
    {
    
        return words.Where(a => Match(a, pattern) && Match(pattern, a)).ToList();
    }

    private bool Match(string a, string pattern)
    {
    
        if (a.Length != pattern.Length) return false;

        Dictionary<char, char> dic = new Dictionary<char, char>();
        
        for (int i = 0; i < pattern.Length; i++)
        {
    
            (char x, char y) = (pattern[i], a[i]);

            if (!dic.ContainsKey(x)) dic.Add(x, y);
            else if (dic[x] != y) return false; 
        }

        return true;
    }
}
原网站

版权声明
本文为[Just be interesting]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071515233913.html