290. 单词规律

给定一种规律 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

 bool wordPattern(string pattern, string str) {

        map p;


        int j = 0;

        string pp;

        for(int i = 0;i < pattern.size();i++)

        {

            if(p.find(pattern[i]) == p.end())

                p[pattern[i]] = 'a'+j++;

            pp += p[pattern[i]];

        }

        map s;

        int js = 0;

        string ss;

        string tmp;

        for(int i = 0;i < str.size();i++)

        {

            if(str[i] != ' ' && i < str.size() - 1)

                tmp += str[i]; 

            else

            {

                if(i == str.size() - 1)

                    tmp += str[i];

                if(s.find(tmp) == s.end())

                    s[tmp] = 'a' + js++;

                ss += s[tmp];

                tmp = "";

            }

        }

        return ss == pp;

    }


另一种:

 bool wordPattern(string pattern, string str) {

        map word_map;

        char used[128] = {0};

        string word;

        int pos = 0;

        str.push_back(' ');

        for(int i = 0;i < str.size();i++)

        {

            if(str[i] == ' ')

            {

                if(pos == pattern.size())

                {

                    return false;

                }

                if(word_map.find(word) == word_map.end())

                {

                    if(used[pattern[pos]] == 1)

                    {

                        return false;

                    }

                    word_map[word] = pattern[pos];

                    used[pattern[pos]] = 1;

                }

                else

                {

                    if(word_map[word] != pattern[pos])

                        return false;

                }

                word = "";

                pos++;

            }

            else

                word += str[i];

        }

        if(pos != pattern.size())

            return false;

        return true;

    }

你可能感兴趣的:(290. 单词规律)