Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单词模式 #26

Open
Aras-ax opened this issue Apr 1, 2019 · 0 comments
Open

单词模式 #26

Aras-ax opened this issue Apr 1, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Apr 1, 2019

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

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

示例1:

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

示例 2:

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

示例 3:

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

示例 4:

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

说明:

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

解答

function wordPattern(pattern, str){
    let words = str.split(' ');
    if(pattern.length !== words.length){
        return false;
    }

    let hashMap1 = {},
        hashMap2 = {};

    for(let i = 0, l = words.length; i < l; i++){
        let key = pattern[i], 
            word = words[i];

        if(hashMap1[key] !== hashMap2[word]){
            return false;
        }

        if(hashMap1[key] === undefined){
            hashMap1[key] = i;
            hashMap2[word] = i;
        }
    }
    return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant