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

[LeetCode] 290. 单词规律 #61

Open
Animenzzzz opened this issue Aug 26, 2019 · 0 comments
Open

[LeetCode] 290. 单词规律 #61

Animenzzzz opened this issue Aug 26, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目吗描述:

给定一种规律 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 包含了由单个空格分隔的小写字母。

解题思路:使用哈希表,建立双重映射。使用两个哈希表,如果其中一个表有映射值而另一个没有,则为false;如果都有映射值,但是对应的值不相等,也是false

C++解题:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<string> words;
        unordered_map<string,char> map1;
        unordered_map<char,string> map2;
        for (int i = 0; i < str.size(); i++)
        {
            string tmp;
            while(i < str.size() && str[i] != ' '){
                tmp = tmp+str[i];
                i++;
            }
            words.push_back(tmp);
        }
        if(words.size() != pattern.size()) return false;
        int word_index = 0;
        for(char kk : pattern){
            if(map2[kk] == "" && !map1[words[word_index]]){
                map2[kk] = words[word_index];
                map1[words[word_index]] = kk;
            }else{
                if(map2[kk] == "" && map1[words[word_index]]) return false;
                else if(map2[kk] != "" && !map1[words[word_index]]) return false;
                else if(map2[kk] != words[word_index] || map1[words[word_index]] != kk) return false;
            }
            word_index++;
        }
        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