leetcode_Word Pattern

来源:互联网 发布:手机vpn 知乎 编辑:程序博客网 时间:2024/06/08 20:12

以下为问题描述:
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.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题目的意思是要我们判断pattern和str是否匹配,匹配的条件是pattern中的字母与str中的单词是否能一一对应,以pattern = “abba”, str = “dog cat cat dog”为例,a与dog对应,b与cat对应。

解题思路:建立pattern哈希表,每当截取一个子串,就将其与哈希表内的字符串比较。

代码

class Solution {public:    bool wordPattern(string pattern, string str) {        vector<string> hashTable(26,"");                //pattern哈希,例如a->0->dog,b->1->cat        int indexOfParttern = 0;                        //pattern下标        int start = 0;                                  //用于截取子串,子串的起始下标        int end = 0;                                    //用于截取子串,子串的结束下标+1        int count = 0;        string sub = str;        while((end = sub.find_first_of(' '))!=-1)        {            sub = sub.substr(0, end);            int hashPos = pattern[indexOfParttern++]-'a';            if (hashTable[hashPos].empty())            {                //如果即将插入哈希表的值在哈希表已经存在则返回false                for (int i = 0; i != hashTable.size(); ++i)                {                    if (hashTable[i] == sub)                    {                        return false;                    }                }                hashTable[hashPos] = sub;            }            else            {                if (hashTable[hashPos]!= sub)                {                    return false;                }            }            start += end+1;            sub = str.substr(start, str.length()-start);            ++count;        }        //若模式串字母个数与str的子串个数不同则false        if (pattern.length() != indexOfParttern + 1)        {            return false;        }        //判断最后一个子串        int hashPos = pattern[indexOfParttern++]-'a';        if (hashTable[hashPos].empty())        {            for (int i = 0; i != hashTable.size(); ++i)            {                if (hashTable[i] == sub)                {                    return false;                }            }            hashTable[hashPos] = sub;        }        else        {            if (hashTable[hashPos]!= sub)            {                return false;            }        }        return true;    }};
0 0