C#LeetCode刷题之#290-单词模式(Word Pattern)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82635211

问题

给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。

这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。

输入: pattern = "abba", str = "dog cat cat dog"

输出: true

输入:pattern = "abba", str = "dog cat cat fish"

输出: false

输入: pattern = "aaaa", str = "dog cat cat dog"

输出: false

输入: pattern = "abba", str = "dog dog dog dog"

输出: false

说明:你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。    


Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Input: pattern = "abba", str = "dog cat cat dog"

Output: true

Input:pattern = "abba", str = "dog cat cat fish"

Output: false

Input: pattern = "aaaa", str = "dog cat cat dog"

Output: false

Input: pattern = "abba", str = "dog dog dog dog"

Output: false

Notes:You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.


示例

public class Program {

    public static void Main(string[] args) {
        string pattern = "abbc";
        string str = "dog cat cat fish";

        var res = WordPattern(pattern, str);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool WordPattern(string pattern, string str) {
        //哈希法
        //总体思路是建立“模式-单词”键值
        //按“模式”完全建立键值对
        //a->dog,b->cat,b->(none),c->fish
        //再还原式匹配单词
        var dic = new Dictionary<int, string>();
        //分隔单词
        var words = str.Split(' ');
        //长度不同时,直接return false
        if(words.Length != pattern.Length) return false;
        //用词典(哈希)记录每种“模式”对应的值
        for(var i = 0; i < pattern.Length; i++) {
            //如果已经存在这个键了,不管
            //如果不存在这个键,则加入词典
            if(!dic.ContainsKey(pattern[i])) {
                //不存在这个键,却存在相应的值,明显模式不匹配
                if(dic.ContainsValue(words[i])) return false;
                //加入词典中
                dic[pattern[i]] = words[i];
            }
        }
        //比对模式和单词
        for(var i = 0; i < pattern.Length; i++) {
            //不同时,匹配失败
            if(dic[pattern[i]] != words[i]) return false;
        }
        //匹配成功
        return true;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

False

分析:

显而易见,以上算法的时间复杂度为: O(n) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82635211
今日推荐